aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore35
-rw-r--r--.gitmodules3
-rw-r--r--.travis.yml4
-rw-r--r--BUILD15
-rw-r--r--CHANGES.txt100
-rw-r--r--Makefile.am68
-rw-r--r--Protobuf.podspec3
-rw-r--r--README.md4
-rw-r--r--WORKSPACE24
-rw-r--r--appveyor.bat2
-rw-r--r--appveyor.yml15
-rwxr-xr-xautogen.sh13
-rw-r--r--benchmarks/Makefile.am11
-rw-r--r--benchmarks/benchmark_messages_proto2.proto2
-rw-r--r--benchmarks/benchmark_messages_proto3.proto2
-rw-r--r--benchmarks/cpp_benchmark.cc242
-rw-r--r--benchmarks/readme.txt22
-rw-r--r--cmake/CMakeLists.txt6
-rw-r--r--cmake/extract_includes.bat.in7
-rw-r--r--cmake/install.cmake2
-rw-r--r--cmake/libprotobuf.cmake5
-rw-r--r--cmake/libprotoc.cmake1
-rw-r--r--cmake/protobuf-config.cmake.in3
-rw-r--r--cmake/protobuf-module.cmake.in1
-rw-r--r--cmake/tests.cmake2
-rw-r--r--composer.json23
-rw-r--r--configure.ac4
-rw-r--r--conformance/Makefile.am18
-rw-r--r--conformance/conformance.proto12
-rwxr-xr-xconformance/conformance_python.py8
-rw-r--r--conformance/conformance_test.cc798
-rw-r--r--conformance/conformance_test.h56
-rw-r--r--conformance/conformance_test_runner.cc12
-rw-r--r--conformance/failure_list_cpp.txt83
-rw-r--r--conformance/failure_list_csharp.txt9
-rw-r--r--conformance/failure_list_java.txt80
-rw-r--r--conformance/failure_list_objc.txt6
-rw-r--r--conformance/failure_list_python.txt66
-rw-r--r--conformance/failure_list_python_cpp.txt98
-rw-r--r--conformance/failure_list_ruby.txt408
-rw-r--r--csharp/Google.Protobuf.Tools.nuspec2
-rw-r--r--csharp/README.md3
-rwxr-xr-xcsharp/build_tools.sh52
-rw-r--r--csharp/src/Google.Protobuf.Conformance/Conformance.cs498
-rw-r--r--csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs12
-rw-r--r--csharp/src/Google.Protobuf.Test/project.json2
-rw-r--r--csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs2
-rw-r--r--csharp/src/Google.Protobuf/JsonFormatter.cs84
-rw-r--r--csharp/src/Google.Protobuf/Reflection/Descriptor.cs132
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs2
-rw-r--r--csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs13
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Any.cs6
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Api.cs6
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs8
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs8
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs12
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs10
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs6
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs2
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs16
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Type.cs2
-rw-r--r--csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs6
-rw-r--r--csharp/src/Google.Protobuf/project.json2
-rw-r--r--docs/swift/DesignDoc.md674
-rw-r--r--docs/third_party.md4
-rw-r--r--editors/protobuf-mode.el3
-rwxr-xr-xgenerate_changelog.py65
-rwxr-xr-xgenerate_descriptor_proto.sh2
-rw-r--r--gmock.BUILD20
-rw-r--r--java/compatibility_tests/v2.5.0/protos/pom.xml2
-rw-r--r--java/core/pom.xml35
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java50
-rw-r--r--java/core/src/main/java/com/google/protobuf/ByteString.java20
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedInputStream.java3523
-rw-r--r--java/core/src/main/java/com/google/protobuf/CodedOutputStream.java400
-rw-r--r--java/core/src/main/java/com/google/protobuf/Descriptors.java31
-rw-r--r--java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java166
-rw-r--r--java/core/src/main/java/com/google/protobuf/Internal.java10
-rw-r--r--java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java16
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapEntry.java9
-rw-r--r--java/core/src/main/java/com/google/protobuf/MapFieldLite.java2
-rw-r--r--java/core/src/main/java/com/google/protobuf/NioByteString.java9
-rw-r--r--java/core/src/main/java/com/google/protobuf/RopeByteString.java1
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormat.java22
-rw-r--r--java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java3
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java31
-rw-r--r--java/core/src/main/java/com/google/protobuf/UnsafeUtil.java119
-rw-r--r--java/core/src/main/java/com/google/protobuf/WireFormat.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/ByteStringTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java802
-rw-r--r--java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java55
-rw-r--r--java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/DescriptorsTest.java15
-rw-r--r--java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java47
-rw-r--r--java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/IntArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyFieldTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteTest.java9
-rw-r--r--java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/LongArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapForProto2Test.java10
-rw-r--r--java/core/src/test/java/com/google/protobuf/MapTest.java170
-rw-r--r--java/core/src/test/java/com/google/protobuf/MessageTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/NioByteStringTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java8
-rw-r--r--java/core/src/test/java/com/google/protobuf/ParserTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/ServiceTest.java8
-rw-r--r--java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/TestUtil.java11
-rw-r--r--java/core/src/test/java/com/google/protobuf/TextFormatTest.java29
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java4
-rw-r--r--java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java3
-rw-r--r--java/core/src/test/java/com/google/protobuf/WireFormatTest.java4
-rw-r--r--java/core/src/test/proto/com/google/protobuf/field_presence_test.proto1
-rw-r--r--java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto37
-rw-r--r--java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto37
-rw-r--r--java/core/src/test/proto/com/google/protobuf/map_test.proto39
-rw-r--r--java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto1
-rw-r--r--java/lite/pom.xml32
-rw-r--r--java/pom.xml4
-rw-r--r--java/util/pom.xml26
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Durations.java182
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/JsonFormat.java43
-rw-r--r--java/util/src/main/java/com/google/protobuf/util/Timestamps.java207
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/JsonFormatTest.java126
-rw-r--r--java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java7
-rw-r--r--java/util/src/test/proto/com/google/protobuf/util/json_test.proto1
-rw-r--r--javanano/pom.xml6
-rw-r--r--javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java2
-rwxr-xr-xjenkins/build_and_run_docker.sh1
-rwxr-xr-xjenkins/buildcmds/pull_request.sh1
-rwxr-xr-xjenkins/buildcmds/pull_request_32.sh16
-rw-r--r--jenkins/docker/Dockerfile63
-rw-r--r--jenkins/docker32/Dockerfile111
-rwxr-xr-xjenkins/pull_request_in_docker.sh14
-rw-r--r--js/binary/proto_test.js2
-rw-r--r--js/commonjs/export.js2
-rw-r--r--js/debug.js3
-rw-r--r--js/debug_test.js2
-rw-r--r--js/map.js22
-rwxr-xr-xjs/maps_test.js301
-rw-r--r--js/message.js166
-rw-r--r--js/message_test.js69
-rw-r--r--js/package.json4
-rw-r--r--js/proto3_test.js2
-rw-r--r--js/test.proto34
-rw-r--r--js/test2.proto6
-rwxr-xr-xobjectivec/DevTools/check_version_stamps.sh67
-rwxr-xr-xobjectivec/DevTools/compile_testing_protos.sh91
-rwxr-xr-xobjectivec/DevTools/full_mac_build.sh48
-rw-r--r--objectivec/GPBArray.h1448
-rw-r--r--objectivec/GPBArray.m20
-rw-r--r--objectivec/GPBBootstrap.h62
-rw-r--r--objectivec/GPBCodedInputStream.h220
-rw-r--r--objectivec/GPBCodedInputStream.m8
-rw-r--r--objectivec/GPBCodedOutputStream.h599
-rw-r--r--objectivec/GPBCodedOutputStream.m39
-rw-r--r--objectivec/GPBDescriptor.h162
-rw-r--r--objectivec/GPBDescriptor.m114
-rw-r--r--objectivec/GPBDescriptor_PackagePrivate.h8
-rw-r--r--objectivec/GPBDictionary.h6538
-rw-r--r--objectivec/GPBExtensionRegistry.h71
-rw-r--r--objectivec/GPBExtensionRegistry.m47
-rw-r--r--objectivec/GPBMessage.h532
-rw-r--r--objectivec/GPBRootObject.h13
-rw-r--r--objectivec/GPBRuntimeTypes.h72
-rw-r--r--objectivec/GPBUnknownField.h63
-rw-r--r--objectivec/GPBUnknownFieldSet.h47
-rw-r--r--objectivec/GPBUnknownFieldSet.m43
-rw-r--r--objectivec/GPBUtilities.h493
-rw-r--r--objectivec/GPBUtilities.m125
-rw-r--r--objectivec/GPBUtilities_PackagePrivate.h19
-rw-r--r--objectivec/GPBWellKnownTypes.h175
-rw-r--r--objectivec/GPBWellKnownTypes.m135
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj22
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme2
-rw-r--r--objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme2
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj34
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme2
-rw-r--r--objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme2
-rw-r--r--objectivec/Tests/GPBCodedOuputStreamTests.m86
-rw-r--r--objectivec/Tests/GPBDescriptorTests.m29
-rw-r--r--objectivec/Tests/GPBMessageTests+Runtime.m399
-rw-r--r--objectivec/Tests/GPBSwiftTests.swift278
-rw-r--r--objectivec/Tests/GPBUnittestProtos.m9
-rw-r--r--objectivec/Tests/GPBUnittestProtos2.m34
-rw-r--r--objectivec/Tests/GPBWellKnownTypesTest.m56
-rw-r--r--objectivec/Tests/unittest_cycle.proto6
-rw-r--r--objectivec/Tests/unittest_extension_chain_a.proto51
-rw-r--r--objectivec/Tests/unittest_extension_chain_b.proto47
-rw-r--r--objectivec/Tests/unittest_extension_chain_c.proto45
-rw-r--r--objectivec/Tests/unittest_extension_chain_d.proto49
-rw-r--r--objectivec/Tests/unittest_extension_chain_e.proto40
-rw-r--r--objectivec/Tests/unittest_extension_chain_f.proto44
-rw-r--r--objectivec/Tests/unittest_extension_chain_g.proto41
-rw-r--r--objectivec/Tests/unittest_objc.proto9
-rw-r--r--objectivec/google/protobuf/Any.pbobjc.h211
-rw-r--r--objectivec/google/protobuf/Any.pbobjc.m10
-rw-r--r--objectivec/google/protobuf/Api.pbobjc.h311
-rw-r--r--objectivec/google/protobuf/Api.pbobjc.m31
-rw-r--r--objectivec/google/protobuf/Duration.pbobjc.h133
-rw-r--r--objectivec/google/protobuf/Duration.pbobjc.m8
-rw-r--r--objectivec/google/protobuf/Empty.pbobjc.h45
-rw-r--r--objectivec/google/protobuf/Empty.pbobjc.m8
-rw-r--r--objectivec/google/protobuf/FieldMask.pbobjc.h433
-rw-r--r--objectivec/google/protobuf/FieldMask.pbobjc.m8
-rw-r--r--objectivec/google/protobuf/SourceContext.pbobjc.h37
-rw-r--r--objectivec/google/protobuf/SourceContext.pbobjc.m8
-rw-r--r--objectivec/google/protobuf/Struct.pbobjc.h131
-rw-r--r--objectivec/google/protobuf/Struct.pbobjc.m14
-rw-r--r--objectivec/google/protobuf/Timestamp.pbobjc.h149
-rw-r--r--objectivec/google/protobuf/Timestamp.pbobjc.m8
-rw-r--r--objectivec/google/protobuf/Type.pbobjc.h281
-rw-r--r--objectivec/google/protobuf/Type.pbobjc.m37
-rw-r--r--objectivec/google/protobuf/Wrappers.pbobjc.h115
-rw-r--r--objectivec/google/protobuf/Wrappers.pbobjc.m24
-rw-r--r--php/README.md99
-rw-r--r--php/ext/google/protobuf/array.c511
-rw-r--r--php/ext/google/protobuf/config.m48
-rw-r--r--php/ext/google/protobuf/def.c616
-rw-r--r--php/ext/google/protobuf/encode_decode.c1257
-rw-r--r--php/ext/google/protobuf/map.c472
-rw-r--r--php/ext/google/protobuf/message.c327
-rw-r--r--php/ext/google/protobuf/package.xml75
-rw-r--r--php/ext/google/protobuf/protobuf.c159
-rw-r--r--php/ext/google/protobuf/protobuf.h528
-rw-r--r--php/ext/google/protobuf/storage.c669
-rw-r--r--php/ext/google/protobuf/test.php15
-rw-r--r--php/ext/google/protobuf/type_check.c430
-rw-r--r--php/ext/google/protobuf/upb.c3797
-rw-r--r--php/ext/google/protobuf/upb.h3036
-rw-r--r--php/ext/google/protobuf/utf8.c68
-rw-r--r--php/ext/google/protobuf/utf8.h36
-rw-r--r--php/src/Google/Protobuf/Internal/DescriptorPool.php162
-rw-r--r--php/src/Google/Protobuf/Internal/EnumBuilderContext.php63
-rw-r--r--php/src/Google/Protobuf/Internal/GPBLabel.php40
-rw-r--r--php/src/Google/Protobuf/Internal/GPBType.php55
-rw-r--r--php/src/Google/Protobuf/Internal/GPBUtil.php196
-rw-r--r--php/src/Google/Protobuf/Internal/GPBWire.php582
-rw-r--r--php/src/Google/Protobuf/Internal/InputStream.php373
-rw-r--r--php/src/Google/Protobuf/Internal/MapEntry.php57
-rw-r--r--php/src/Google/Protobuf/Internal/MapField.php321
-rw-r--r--php/src/Google/Protobuf/Internal/Message.php679
-rw-r--r--php/src/Google/Protobuf/Internal/MessageBuilderContext.php120
-rw-r--r--php/src/Google/Protobuf/Internal/OneofField.php77
-rw-r--r--php/src/Google/Protobuf/Internal/OutputStream.php164
-rw-r--r--php/src/Google/Protobuf/Internal/RepeatedField.php303
-rw-r--r--php/src/Google/Protobuf/descriptor.php545
-rw-r--r--php/src/Google/Protobuf/descriptor_internal.pb.php2532
-rw-r--r--php/src/phpdoc.dist.xml15
-rw-r--r--php/tests/array_test.php940
-rw-r--r--php/tests/autoload.php4
-rw-r--r--php/tests/encode_decode_test.php136
-rw-r--r--php/tests/generated_class_test.php611
-rw-r--r--php/tests/map_field_test.php680
-rw-r--r--php/tests/memory_leak_test.php73
-rw-r--r--php/tests/php_implementation_test.php481
-rw-r--r--php/tests/test.pb.php1385
-rw-r--r--php/tests/test.proto136
-rwxr-xr-xphp/tests/test.sh28
-rw-r--r--php/tests/test_base.php106
-rw-r--r--php/tests/test_include.pb.php36
-rw-r--r--php/tests/test_include.proto7
-rw-r--r--php/tests/test_no_namespace.pb.php34
-rw-r--r--php/tests/test_no_namespace.proto5
-rw-r--r--php/tests/test_util.php440
-rw-r--r--phpunit.xml13
-rwxr-xr-xpost_process_dist.sh2
-rw-r--r--protobuf.bzl86
-rw-r--r--protoc-artifacts/pom.xml2
-rwxr-xr-xpython/google/protobuf/__init__.py2
-rwxr-xr-xpython/google/protobuf/descriptor.py49
-rw-r--r--python/google/protobuf/descriptor_pool.py138
-rw-r--r--python/google/protobuf/internal/any_test.proto14
-rwxr-xr-xpython/google/protobuf/internal/containers.py21
-rw-r--r--python/google/protobuf/internal/descriptor_pool_test.py5
-rwxr-xr-xpython/google/protobuf/internal/descriptor_test.py19
-rwxr-xr-xpython/google/protobuf/internal/generator_test.py3
-rw-r--r--python/google/protobuf/internal/json_format_test.py78
-rwxr-xr-xpython/google/protobuf/internal/message_test.py45
-rwxr-xr-xpython/google/protobuf/internal/python_message.py11
-rwxr-xr-xpython/google/protobuf/internal/reflection_test.py43
-rw-r--r--python/google/protobuf/internal/testing_refleaks.py128
-rwxr-xr-xpython/google/protobuf/internal/text_format_test.py25
-rwxr-xr-xpython/google/protobuf/internal/unknown_fields_test.py107
-rw-r--r--python/google/protobuf/internal/well_known_types.py75
-rw-r--r--python/google/protobuf/internal/well_known_types_test.py132
-rw-r--r--python/google/protobuf/json_format.py95
-rwxr-xr-xpython/google/protobuf/message.py9
-rw-r--r--python/google/protobuf/message_factory.py11
-rw-r--r--python/google/protobuf/pyext/descriptor.cc22
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.cc59
-rw-r--r--python/google/protobuf/pyext/descriptor_pool.h35
-rw-r--r--python/google/protobuf/pyext/extension_dict.cc78
-rw-r--r--python/google/protobuf/pyext/extension_dict.h43
-rw-r--r--python/google/protobuf/pyext/map_container.cc95
-rw-r--r--python/google/protobuf/pyext/map_container.h12
-rw-r--r--python/google/protobuf/pyext/message.cc223
-rw-r--r--python/google/protobuf/pyext/message.h33
-rw-r--r--python/google/protobuf/pyext/message_factory.cc214
-rw-r--r--python/google/protobuf/pyext/message_factory.h103
-rw-r--r--python/google/protobuf/pyext/repeated_composite_container.cc2
-rw-r--r--python/google/protobuf/symbol_database.py3
-rwxr-xr-xpython/google/protobuf/text_format.py16
-rw-r--r--python/tox.ini2
-rw-r--r--ruby/Gemfile.lock30
-rw-r--r--ruby/ext/google/protobuf_c/encode_decode.c62
-rw-r--r--ruby/ext/google/protobuf_c/protobuf.c2
-rw-r--r--ruby/ext/google/protobuf_c/protobuf.h2
-rw-r--r--ruby/ext/google/protobuf_c/repeated_field.c12
-rw-r--r--ruby/ext/google/protobuf_c/upb.c2
-rw-r--r--ruby/google-protobuf.gemspec11
-rw-r--r--ruby/lib/google/protobuf.rb2
-rw-r--r--ruby/pom.xml2
-rw-r--r--ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java19
-rw-r--r--ruby/tests/basic.rb5
-rwxr-xr-xruby/travis-test.sh4
-rw-r--r--src/Makefile.am234
-rw-r--r--src/google/protobuf/any.pb.cc131
-rw-r--r--src/google/protobuf/any.pb.h20
-rw-r--r--src/google/protobuf/any.proto1
-rw-r--r--src/google/protobuf/api.pb.cc414
-rw-r--r--src/google/protobuf/api.pb.h61
-rw-r--r--src/google/protobuf/api.proto1
-rwxr-xr-xsrc/google/protobuf/arena.cc10
-rw-r--r--src/google/protobuf/arena.h24
-rw-r--r--src/google/protobuf/arena_unittest.cc46
-rw-r--r--src/google/protobuf/compiler/code_generator.cc28
-rw-r--r--src/google/protobuf/compiler/code_generator.h41
-rw-r--r--src/google/protobuf/compiler/command_line_interface.cc104
-rw-r--r--src/google/protobuf/compiler/command_line_interface.h35
-rw-r--r--src/google/protobuf/compiler/command_line_interface_unittest.cc129
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc1
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum.cc2
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.cc39
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_enum_field.h1
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_extension.cc30
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_field.h7
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_file.cc163
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.cc41
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_helpers.h19
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_map_field.cc3
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.cc892
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message.h10
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_message_field.cc49
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_primitive_field.cc47
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_primitive_field.h1
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.cc104
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_string_field.h1
-rw-r--r--src/google/protobuf/compiler/cpp/cpp_unittest.cc8
-rw-r--r--src/google/protobuf/compiler/csharp/csharp_generator.h6
-rw-r--r--src/google/protobuf/compiler/java/java_file.cc2
-rw-r--r--src/google/protobuf/compiler/java/java_map_field.cc38
-rw-r--r--src/google/protobuf/compiler/java/java_map_field_lite.cc6
-rw-r--r--src/google/protobuf/compiler/java/java_message.cc2
-rw-r--r--src/google/protobuf/compiler/java/java_message_builder.cc13
-rw-r--r--src/google/protobuf/compiler/java/java_message_field_lite.cc1
-rw-r--r--src/google/protobuf/compiler/java/java_message_lite.cc4
-rw-r--r--src/google/protobuf/compiler/java/java_service.cc20
-rw-r--r--src/google/protobuf/compiler/java/java_service.h3
-rw-r--r--src/google/protobuf/compiler/java/java_shared_code_generator.cc2
-rwxr-xr-xsrc/google/protobuf/compiler/js/js_generator.cc819
-rwxr-xr-xsrc/google/protobuf/compiler/js/js_generator.h93
-rw-r--r--src/google/protobuf/compiler/main.cc20
-rw-r--r--src/google/protobuf/compiler/mock_code_generator.cc8
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_enum.cc18
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc14
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_extension.cc4
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_field.cc8
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_file.cc469
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_file.h15
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_generator.cc51
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_generator.h15
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.cc410
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_helpers.h69
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_map_field.cc2
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_message.cc18
-rw-r--r--src/google/protobuf/compiler/objectivec/objectivec_oneof.cc6
-rw-r--r--src/google/protobuf/compiler/parser.cc2
-rw-r--r--src/google/protobuf/compiler/php/php_generator.cc781
-rw-r--r--src/google/protobuf/compiler/php/php_generator.h57
-rw-r--r--src/google/protobuf/compiler/plugin.cc39
-rw-r--r--src/google/protobuf/compiler/plugin.pb.cc355
-rw-r--r--src/google/protobuf/compiler/plugin.pb.h57
-rw-r--r--src/google/protobuf/compiler/python/python_generator.cc19
-rw-r--r--src/google/protobuf/compiler/ruby/ruby_generator.h6
-rw-r--r--src/google/protobuf/compiler/subprocess.cc12
-rw-r--r--src/google/protobuf/descriptor.cc207
-rw-r--r--src/google/protobuf/descriptor.h9
-rw-r--r--src/google/protobuf/descriptor.pb.cc3142
-rw-r--r--src/google/protobuf/descriptor.pb.h490
-rw-r--r--src/google/protobuf/descriptor.proto23
-rw-r--r--src/google/protobuf/descriptor_unittest.cc85
-rw-r--r--src/google/protobuf/duration.pb.cc148
-rw-r--r--src/google/protobuf/duration.pb.h33
-rw-r--r--src/google/protobuf/duration.proto8
-rw-r--r--src/google/protobuf/dynamic_message.cc62
-rw-r--r--src/google/protobuf/empty.pb.cc106
-rw-r--r--src/google/protobuf/empty.pb.h20
-rw-r--r--src/google/protobuf/empty.proto1
-rw-r--r--src/google/protobuf/extension_set.cc21
-rw-r--r--src/google/protobuf/extension_set.h8
-rw-r--r--src/google/protobuf/extension_set_heavy.cc10
-rw-r--r--src/google/protobuf/extension_set_unittest.cc2
-rw-r--r--src/google/protobuf/field_mask.pb.cc126
-rw-r--r--src/google/protobuf/field_mask.pb.h20
-rw-r--r--src/google/protobuf/field_mask.proto7
-rw-r--r--src/google/protobuf/generated_message_reflection.cc165
-rw-r--r--src/google/protobuf/generated_message_reflection.h34
-rw-r--r--src/google/protobuf/generated_message_util.cc6
-rw-r--r--src/google/protobuf/generated_message_util.h70
-rw-r--r--src/google/protobuf/has_bits.h72
-rw-r--r--src/google/protobuf/io/coded_stream.cc45
-rw-r--r--src/google/protobuf/io/coded_stream.h14
-rw-r--r--src/google/protobuf/io/coded_stream_unittest.cc1
-rw-r--r--src/google/protobuf/io/zero_copy_stream_impl.h12
-rw-r--r--src/google/protobuf/map.h21
-rw-r--r--src/google/protobuf/map_entry.h4
-rw-r--r--src/google/protobuf/map_entry_lite.h6
-rw-r--r--src/google/protobuf/map_type_handler.h4
-rw-r--r--src/google/protobuf/message.cc10
-rw-r--r--src/google/protobuf/message.h10
-rw-r--r--src/google/protobuf/message_lite.cc39
-rw-r--r--src/google/protobuf/message_lite.h7
-rw-r--r--src/google/protobuf/message_unittest.cc36
-rw-r--r--src/google/protobuf/metadata.h4
-rwxr-xr-xsrc/google/protobuf/reflection.h29
-rw-r--r--src/google/protobuf/reflection_ops.h2
-rw-r--r--src/google/protobuf/repeated_field.cc18
-rw-r--r--src/google/protobuf/repeated_field.h55
-rw-r--r--src/google/protobuf/repeated_field_unittest.cc46
-rw-r--r--src/google/protobuf/source_context.pb.cc115
-rw-r--r--src/google/protobuf/source_context.pb.h20
-rw-r--r--src/google/protobuf/source_context.proto1
-rw-r--r--src/google/protobuf/struct.pb.cc574
-rw-r--r--src/google/protobuf/struct.pb.h260
-rw-r--r--src/google/protobuf/struct.proto2
-rw-r--r--src/google/protobuf/stubs/atomicops.h10
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h (renamed from src/google/protobuf/stubs/atomicops_internals_pnacl.h)6
-rw-r--r--src/google/protobuf/stubs/atomicops_internals_generic_gcc.h28
-rw-r--r--src/google/protobuf/stubs/callback.h4
-rw-r--r--src/google/protobuf/stubs/common.h10
-rw-r--r--src/google/protobuf/stubs/common_unittest.cc2
-rw-r--r--src/google/protobuf/stubs/once_unittest.cc5
-rw-r--r--src/google/protobuf/stubs/platform_macros.h4
-rw-r--r--src/google/protobuf/stubs/port.h55
-rw-r--r--src/google/protobuf/stubs/strutil.cc15
-rw-r--r--src/google/protobuf/stubs/strutil.h4
-rw-r--r--src/google/protobuf/stubs/substitute.cc4
-rw-r--r--src/google/protobuf/stubs/type_traits.h2
-rw-r--r--src/google/protobuf/testing/file.cc17
-rw-r--r--src/google/protobuf/text_format.cc35
-rw-r--r--src/google/protobuf/text_format.h12
-rw-r--r--src/google/protobuf/text_format_unittest.cc99
-rw-r--r--src/google/protobuf/timestamp.pb.cc126
-rw-r--r--src/google/protobuf/timestamp.pb.h20
-rw-r--r--src/google/protobuf/timestamp.proto9
-rw-r--r--src/google/protobuf/type.pb.cc1392
-rw-r--r--src/google/protobuf/type.pb.h629
-rw-r--r--src/google/protobuf/type.proto2
-rw-r--r--src/google/protobuf/unittest.proto8
-rw-r--r--src/google/protobuf/unknown_field_set.cc7
-rw-r--r--src/google/protobuf/unknown_field_set.h16
-rw-r--r--src/google/protobuf/util/field_comparator.h4
-rw-r--r--src/google/protobuf/util/field_mask_util.cc5
-rw-r--r--src/google/protobuf/util/field_mask_util.h2
-rw-r--r--src/google/protobuf/util/internal/datapiece.cc32
-rw-r--r--src/google/protobuf/util/internal/datapiece.h33
-rw-r--r--src/google/protobuf/util/internal/default_value_objectwriter.cc47
-rw-r--r--src/google/protobuf/util/internal/error_listener.h4
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.cc21
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter.h20
-rw-r--r--src/google/protobuf/util/internal/json_objectwriter_test.cc4
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.cc46
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser.h8
-rw-r--r--src/google/protobuf/util/internal/json_stream_parser_test.cc45
-rw-r--r--src/google/protobuf/util/internal/object_writer.h7
-rw-r--r--src/google/protobuf/util/internal/proto_writer.cc9
-rw-r--r--src/google/protobuf/util/internal/proto_writer.h8
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.cc19
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource.h43
-rw-r--r--src/google/protobuf/util/internal/protostream_objectsource_test.cc66
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.cc141
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter.h62
-rw-r--r--src/google/protobuf/util/internal/protostream_objectwriter_test.cc459
-rw-r--r--src/google/protobuf/util/internal/testdata/anys.proto69
-rw-r--r--src/google/protobuf/util/internal/testdata/books.proto5
-rw-r--r--src/google/protobuf/util/internal/testdata/maps.proto76
-rw-r--r--src/google/protobuf/util/internal/testdata/oneofs.proto31
-rw-r--r--src/google/protobuf/util/internal/testdata/proto3.proto42
-rw-r--r--src/google/protobuf/util/internal/testdata/struct.proto86
-rw-r--r--src/google/protobuf/util/internal/testdata/timestamp_duration.proto47
-rw-r--r--src/google/protobuf/util/internal/utility.cc62
-rw-r--r--src/google/protobuf/util/internal/utility.h11
-rw-r--r--src/google/protobuf/util/json_util_test.cc28
-rw-r--r--src/google/protobuf/util/message_differencer.cc6
-rw-r--r--src/google/protobuf/util/message_differencer.h126
-rw-r--r--src/google/protobuf/util/package_info.h46
-rw-r--r--src/google/protobuf/util/time_util.cc4
-rw-r--r--src/google/protobuf/util/time_util.h3
-rw-r--r--src/google/protobuf/util/type_resolver.h2
-rw-r--r--src/google/protobuf/util/type_resolver_util.h2
-rw-r--r--src/google/protobuf/wire_format.cc39
-rw-r--r--src/google/protobuf/wire_format.h17
-rw-r--r--src/google/protobuf/wire_format_lite.cc2
-rw-r--r--src/google/protobuf/wire_format_lite.h53
-rw-r--r--src/google/protobuf/wire_format_lite_inl.h46
-rw-r--r--src/google/protobuf/wrappers.pb.cc740
-rw-r--r--src/google/protobuf/wrappers.pb.h140
-rw-r--r--src/google/protobuf/wrappers.proto1
-rwxr-xr-xtests.sh138
m---------third_party/benchmark0
527 files changed, 53377 insertions, 15883 deletions
diff --git a/.gitignore b/.gitignore
index 5cb8cba9..ea865f4e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,6 +64,8 @@ src/protoc
src/unittest_proto_middleman
# Generated test scaffolding
+src/no_warning_test.cc
+src/no-warning-test
src/protobuf*-test
src/test_plugin
src/testzip.*
@@ -77,7 +79,8 @@ src/**/*.log
src/**/*.trs
# JavaBuild output.
-java/target
+java/core/target
+java/util/target
javanano/target
# Windows native output.
@@ -108,8 +111,36 @@ conformance/conformance.pb.cc
conformance/conformance.pb.h
conformance/Conformance.pbobjc.h
conformance/Conformance.pbobjc.m
-conformance/conformance.rb
+conformance/conformance_pb.rb
+conformance/failing_tests.txt
conformance/google/
conformance/javac_middleman
conformance/lite/
+conformance/nonexistent_tests.txt
conformance/protoc_middleman
+conformance/succeeding_tests.txt
+
+# php test output
+composer.lock
+php/tests/test.pb.php
+php/tests/test_include.pb.php
+php/ext/google/protobuf/.libs/
+php/ext/google/protobuf/Makefile.fragments
+php/ext/google/protobuf/Makefile.global
+php/ext/google/protobuf/Makefile.objects
+php/ext/google/protobuf/acinclude.m4
+php/ext/google/protobuf/build/
+php/ext/google/protobuf/config.h
+php/ext/google/protobuf/config.nice
+php/ext/google/protobuf/configure.in
+php/ext/google/protobuf/mkinstalldirs
+php/ext/google/protobuf/run-tests.php
+vendor/
+
+# JavaScript artifacts
+js/commonjs_out/
+js/deps.js
+js/google-protobuf.js
+js/google/
+js/node_modules/
+js/testproto_libs.js
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 00000000..55a47cea
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "third_party/benchmark"]
+ path = third_party/benchmark
+ url = https://github.com/google/benchmark.git
diff --git a/.travis.yml b/.travis.yml
index 094235e0..bd9a5dfb 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,4 +1,5 @@
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
@@ -7,7 +8,7 @@ language: cpp
os:
- osx
# The Objective C build needs Xcode 7.0 or later.
-osx_image: xcode7.3
+osx_image: xcode8
script:
- ./tests.sh $CONFIG
env:
@@ -30,6 +31,7 @@ env:
- CONFIG=ruby21
- CONFIG=ruby22
- CONFIG=jruby
+ - CONFIG=php5.6_mac
matrix:
exclude:
# It's nontrivial to programmatically install a new JDK from the command
diff --git a/BUILD b/BUILD
index 0941d8c4..f17c500a 100644
--- a/BUILD
+++ b/BUILD
@@ -2,6 +2,8 @@
licenses(["notice"])
+exports_files(["LICENSE"])
+
################################################################################
# Protobuf Runtime Library
################################################################################
@@ -12,7 +14,7 @@ COPTS = [
"-Wwrite-strings",
"-Woverloaded-virtual",
"-Wno-sign-compare",
- "-Wno-error=unused-function",
+ "-Wno-unused-function",
]
config_setting(
@@ -314,6 +316,7 @@ cc_library(
"src/google/protobuf/compiler/objectivec/objectivec_message_field.cc",
"src/google/protobuf/compiler/objectivec/objectivec_oneof.cc",
"src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc",
+ "src/google/protobuf/compiler/php/php_generator.cc",
"src/google/protobuf/compiler/plugin.cc",
"src/google/protobuf/compiler/plugin.pb.cc",
"src/google/protobuf/compiler/python/python_generator.cc",
@@ -388,8 +391,10 @@ RELATIVE_TEST_PROTOS = [
"google/protobuf/util/internal/testdata/field_mask.proto",
"google/protobuf/util/internal/testdata/maps.proto",
"google/protobuf/util/internal/testdata/oneofs.proto",
+ "google/protobuf/util/internal/testdata/proto3.proto",
"google/protobuf/util/internal/testdata/struct.proto",
"google/protobuf/util/internal/testdata/timestamp_duration.proto",
+ "google/protobuf/util/internal/testdata/wrappers.proto",
"google/protobuf/util/json_format_proto3.proto",
"google/protobuf/util/message_differencer_unittest.proto",
]
@@ -572,7 +577,7 @@ py_library(
)
cc_binary(
- name = "internal/_api_implementation.so",
+ name = "python/google/protobuf/internal/_api_implementation.so",
srcs = ["python/google/protobuf/internal/api_implementation.cc"],
copts = COPTS + [
"-DPYTHON_PROTO2_CPP_IMPL_V2",
@@ -586,7 +591,7 @@ cc_binary(
)
cc_binary(
- name = "pyext/_message.so",
+ name = "python/google/protobuf/pyext/_message.so",
srcs = glob([
"python/google/protobuf/pyext/*.cc",
"python/google/protobuf/pyext/*.h",
@@ -648,8 +653,8 @@ py_proto_library(
data = select({
"//conditions:default": [],
":use_fast_cpp_protos": [
- ":internal/_api_implementation.so",
- ":pyext/_message.so",
+ ":python/google/protobuf/internal/_api_implementation.so",
+ ":python/google/protobuf/pyext/_message.so",
],
}),
default_runtime = "",
diff --git a/CHANGES.txt b/CHANGES.txt
index 822136c0..7fb2da2e 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,3 +1,103 @@
+2016-09-23 version 3.1.0 (C++/Java/Python/PHP/Ruby/Objective-C/C#/JavaScript/Lite)
+ General
+ * Proto3 support in PHP (alpha).
+ * Various bug fixes.
+
+ C++
+ * Added MessageLite::ByteSizeLong() that’s equivalent to
+ MessageLite::ByteSize() but returns the value in size_t. Useful to check
+ whether a message is over the 2G size limit that protobuf can support.
+ * Moved default_instances to global variables. This allows default_instance
+ addresses to be known at compile time.
+ * Adding missing generic gcc 64-bit atomicops.
+ * Restore New*Callback into google::protobuf namespace since these are used
+ by the service stubs code
+ * JSON support.
+ * Fixed some conformance issues.
+ * Fixed a JSON serialization bug for bytes fields.
+
+ Java
+ * Fixed a bug in TextFormat that doesn’t accept empty repeated fields (i.e.,
+ “field: [ ]”).
+ * JSON support
+ * Fixed JsonFormat to do correct snake_case-to-camelCase conversion for
+ non-style-conforming field names.
+ * Fixed JsonFormat to parse empty Any message correctly.
+ * Added an option to JsonFormat.Parser to ignore unknown fields.
+ * Experimental API
+ * Added UnsafeByteOperations.unsafeWrap(byte[]) to wrap a byte array into
+ ByteString without copy.
+
+ Python
+ * JSON support
+ * Fixed some conformance issues.
+
+ PHP (Alpha)
+ * We have added the proto3 support for PHP via both a pure PHP package and a
+ native c extension. The pure PHP package is intended to provide usability
+ to wider range of PHP platforms, while the c extension is intended to
+ provide higher performance. Both implementations provide the same runtime
+ APIs and share the same generated code. Users don’t need to re-generate
+ code for the same proto definition when they want to switch the
+ implementation later. The pure PHP package is included in the php/src
+ directory, and the c extension is included in the php/ext directory.
+
+ Both implementations provide idiomatic PHP APIs:
+ * All messages and enums are defined as PHP classes.
+ * All message fields can only be accessed via getter/setter.
+ * Both repeated field elements and map elements are stored in containers
+ that act like a normal PHP array.
+
+ Unlike several existing third-party PHP implementations for protobuf, our
+ implementations are built on a "strongly-typed" philosophy: message fields
+ and array/map containers will throw exceptions eagerly when values of the
+ incorrect type (not including those that can be type converted, e.g.,
+ double <-> integer <-> numeric string) are inserted.
+
+ Currently, pure PHP runtime supports php5.5, 5.6 and 7 on linux. C
+ extension runtime supports php5.5 and 5.6 on linux.
+
+ See php/README.md for more details about installment. See
+ https://developers.google.com/protocol-buffers/docs/phptutorial for more
+ details about APIs.
+
+ Objective-C
+ * Helpers are now provided for working the the Any well known type (see
+ GPBWellKnownTypes.h for the api additions).
+ * Some improvements in startup code (especially when extensions aren’t used).
+
+ Javascript
+ * Fixed missing import of jspb.Map
+ * Fixed valueWriterFn variable name
+
+ Ruby
+ * Fixed hash computation for JRuby's RubyMessage
+ * Make sure map parsing frames are GC-rooted.
+ * Added API support for well-known types.
+
+ C#
+ * Removed check on dependency in the C# reflection API.
+
+2016-09-06 version 3.0.2 (C++/Java/Python/Ruby/Objective-C/C#/JavaScript/Lite)
+ General
+ * Various bug fixes.
+
+ Objective C
+ * Fix for oneofs in proto3 syntax files where fields were set to the zero
+ value.
+ * Fix for embedded null character in strings.
+ * CocoaDocs support
+
+ Ruby
+ * Fixed memory corruption bug in parsing that could occur under GC pressure.
+
+ Javascript
+ * jspb.Map is now properly exported to CommonJS modules.
+
+ C#
+ * Removed legacy_enum_values flag.
+
+
2016-07-27 version 3.0.0 (C++/Java/Python/Ruby/Objective-C/C#/JavaScript/Lite)
General
* This log only contains changes since the beta-4 release. Summarized change
diff --git a/Makefile.am b/Makefile.am
index 41d25823..4763d949 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -54,6 +54,7 @@ csharp_EXTRA_DIST= \
csharp/Google.Protobuf.Tools.nuspec \
csharp/README.md \
csharp/build_packages.bat \
+ csharp/build_tools.sh \
csharp/buildall.sh \
csharp/generate_protos.sh \
csharp/keys/Google.Protobuf.public.snk \
@@ -534,6 +535,7 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/GPBTestUtilities.h \
objectivec/Tests/GPBTestUtilities.m \
objectivec/Tests/GPBUnittestProtos.m \
+ objectivec/Tests/GPBUnittestProtos2.m \
objectivec/Tests/GPBUnknownFieldSetTest.m \
objectivec/Tests/GPBUtilitiesTests.m \
objectivec/Tests/GPBWellKnownTypesTest.m \
@@ -555,6 +557,13 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/text_format_map_unittest_data.txt \
objectivec/Tests/text_format_unittest_data.txt \
objectivec/Tests/unittest_cycle.proto \
+ objectivec/Tests/unittest_extension_chain_a.proto \
+ objectivec/Tests/unittest_extension_chain_b.proto \
+ objectivec/Tests/unittest_extension_chain_c.proto \
+ objectivec/Tests/unittest_extension_chain_d.proto \
+ objectivec/Tests/unittest_extension_chain_e.proto \
+ objectivec/Tests/unittest_extension_chain_f.proto \
+ objectivec/Tests/unittest_extension_chain_g.proto \
objectivec/Tests/unittest_objc.proto \
objectivec/Tests/unittest_objc_startup.proto \
objectivec/Tests/unittest_runtime_proto2.proto \
@@ -563,6 +572,58 @@ objectivec_EXTRA_DIST= \
objectivec/Tests/UnitTests-Info.plist \
Protobuf.podspec
+php_EXTRA_DIST= \
+ php/src/phpdoc.dist.xml \
+ php/src/Google/Protobuf/Internal/DescriptorPool.php \
+ php/src/Google/Protobuf/Internal/OneofField.php \
+ php/src/Google/Protobuf/Internal/MapEntry.php \
+ php/src/Google/Protobuf/Internal/InputStream.php \
+ php/src/Google/Protobuf/Internal/OutputStream.php \
+ php/src/Google/Protobuf/Internal/MessageBuilderContext.php \
+ php/src/Google/Protobuf/Internal/MapField.php \
+ php/src/Google/Protobuf/Internal/RepeatedField.php \
+ php/src/Google/Protobuf/Internal/Message.php \
+ php/src/Google/Protobuf/Internal/GPBWire.php \
+ php/src/Google/Protobuf/Internal/GPBType.php \
+ php/src/Google/Protobuf/Internal/GPBLabel.php \
+ php/src/Google/Protobuf/Internal/EnumBuilderContext.php \
+ php/src/Google/Protobuf/Internal/GPBUtil.php \
+ php/src/Google/Protobuf/descriptor_internal.pb.php \
+ php/src/Google/Protobuf/descriptor.php \
+ php/tests/encode_decode_test.php \
+ php/tests/test.sh \
+ php/tests/generated_class_test.php \
+ php/tests/array_test.php \
+ php/tests/php_implementation_test.php \
+ php/tests/test_include.proto \
+ php/tests/test_include.pb.php \
+ php/tests/map_field_test.php \
+ php/tests/test_base.php \
+ php/tests/test_no_namespace.proto \
+ php/tests/test_no_namespace.pb.php \
+ php/tests/test_util.php \
+ php/tests/test.proto \
+ php/tests/test.pb.php \
+ php/tests/memory_leak_test.php \
+ php/README.md \
+ php/ext/google/protobuf/utf8.h \
+ php/ext/google/protobuf/message.c \
+ php/ext/google/protobuf/utf8.c \
+ php/ext/google/protobuf/package.xml \
+ php/ext/google/protobuf/upb.h \
+ php/ext/google/protobuf/array.c \
+ php/ext/google/protobuf/encode_decode.c \
+ php/ext/google/protobuf/protobuf.h \
+ php/ext/google/protobuf/type_check.c \
+ php/ext/google/protobuf/def.c \
+ php/ext/google/protobuf/storage.c \
+ php/ext/google/protobuf/map.c \
+ php/ext/google/protobuf/config.m4 \
+ php/ext/google/protobuf/upb.c \
+ php/ext/google/protobuf/protobuf.c \
+ phpunit.xml \
+ composer.json
+
python_EXTRA_DIST= \
python/MANIFEST.in \
python/google/__init__.py \
@@ -609,6 +670,7 @@ python_EXTRA_DIST= \
python/google/protobuf/internal/symbol_database_test.py \
python/google/protobuf/internal/test_bad_identifiers.proto \
python/google/protobuf/internal/test_util.py \
+ python/google/protobuf/internal/testing_refleaks.py \
python/google/protobuf/internal/text_encoding_test.py \
python/google/protobuf/internal/text_format_test.py \
python/google/protobuf/internal/type_checkers.py \
@@ -640,6 +702,8 @@ python_EXTRA_DIST= \
python/google/protobuf/pyext/map_container.h \
python/google/protobuf/pyext/message.cc \
python/google/protobuf/pyext/message.h \
+ python/google/protobuf/pyext/message_factory.cc \
+ python/google/protobuf/pyext/message_factory.h \
python/google/protobuf/pyext/message_module.cc \
python/google/protobuf/pyext/proto2_api_test.proto \
python/google/protobuf/pyext/python.proto \
@@ -664,7 +728,6 @@ python_EXTRA_DIST= \
ruby_EXTRA_DIST= \
ruby/Gemfile \
- ruby/Gemfile.lock \
ruby/.gitignore \
ruby/README.md \
ruby/Rakefile \
@@ -741,6 +804,7 @@ js_EXTRA_DIST= \
js/gulpfile.js \
js/jasmine.json \
js/map.js \
+ js/maps_test.js \
js/message.js \
js/message_test.js \
js/node_loader.js \
@@ -756,7 +820,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) $(python_EXTRA_DIST) $(ruby_EXTRA_DIST) $(js_EXTRA_DIST)
+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)
EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
autogen.sh \
diff --git a/Protobuf.podspec b/Protobuf.podspec
index 642fc3e2..217f6d20 100644
--- a/Protobuf.podspec
+++ b/Protobuf.podspec
@@ -5,7 +5,7 @@
# dependent projects use the :git notation to refer to the library.
Pod::Spec.new do |s|
s.name = 'Protobuf'
- s.version = '3.0.0'
+ s.version = '3.1.0'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/google/protobuf'
s.license = 'New BSD'
@@ -36,5 +36,6 @@ Pod::Spec.new do |s|
s.ios.deployment_target = '7.1'
s.osx.deployment_target = '10.9'
+ s.watchos.deployment_target = '2.0'
s.requires_arc = false
end
diff --git a/README.md b/README.md
index ba9c589d..80e556b1 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
Protocol Buffers - Google's data interchange format
===================================================
-[![Build Status](https://travis-ci.org/google/protobuf.svg?branch=master)](https://travis-ci.org/google/protobuf) [![Build status](https://ci.appveyor.com/api/projects/status/73ctee6ua4w2ruin?svg=true)](https://ci.appveyor.com/project/protobuf/protobuf)
+[![Build Status](https://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)
Copyright 2008 Google Inc.
@@ -65,7 +65,7 @@ how to install protobuf runtime for that specific language:
| JavaScript | [js](js) |
| Ruby | [ruby](ruby) |
| Go | [golang/protobuf](https://github.com/golang/protobuf) |
-| PHP | TBD |
+| PHP | [php](php) |
Usage
diff --git a/WORKSPACE b/WORKSPACE
index 065dc819..2a49e372 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -1,15 +1,15 @@
-new_http_archive(
- name = "gmock_archive",
- url = "https://googlemock.googlecode.com/files/gmock-1.7.0.zip",
- sha256 = "26fcbb5925b74ad5fc8c26b0495dfc96353f4d553492eb97e85a8a6d2f43095b",
+new_git_repository(
+ name = "googletest",
build_file = "gmock.BUILD",
+ remote = "https://github.com/google/googletest",
+ tag = "release-1.8.0",
)
new_http_archive(
name = "six_archive",
- url = "https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55",
- sha256 = "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a",
build_file = "six.BUILD",
+ sha256 = "105f8d68616f8248e24bf0e9372ef04d3cc10104f1980f54d57b2ce73a5ad56a",
+ url = "https://pypi.python.org/packages/source/s/six/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55",
)
bind(
@@ -19,12 +19,12 @@ bind(
bind(
name = "gtest",
- actual = "@gmock_archive//:gtest",
+ actual = "@googletest//:gtest",
)
bind(
name = "gtest_main",
- actual = "@gmock_archive//:gtest_main",
+ actual = "@googletest//:gtest_main",
)
bind(
@@ -33,8 +33,8 @@ bind(
)
maven_jar(
- name = "guava_maven",
- artifact = "com.google.guava:guava:18.0",
+ name = "guava_maven",
+ artifact = "com.google.guava:guava:18.0",
)
bind(
@@ -43,8 +43,8 @@ bind(
)
maven_jar(
- name = "gson_maven",
- artifact = "com.google.code.gson:gson:2.3",
+ name = "gson_maven",
+ artifact = "com.google.code.gson:gson:2.7",
)
bind(
diff --git a/appveyor.bat b/appveyor.bat
index 0e6dd520..916f4434 100644
--- a/appveyor.bat
+++ b/appveyor.bat
@@ -10,7 +10,7 @@ goto :error
echo Building C++
mkdir build_msvc
cd build_msvc
-cmake -G "%generator%" -Dprotobuf_BUILD_SHARED_LIBS=%BUILD_DLL% ../cmake
+cmake -G "%generator%" -Dprotobuf_BUILD_SHARED_LIBS=%BUILD_DLL% -Dprotobuf_UNICODE=%UNICODE% ../cmake
msbuild protobuf.sln /p:Platform=%vcplatform% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" || goto error
cd %configuration%
tests.exe || goto error
diff --git a/appveyor.yml b/appveyor.yml
index ce797c69..08d087b6 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -11,6 +11,7 @@ environment:
matrix:
- language: cpp
BUILD_DLL: ON
+ UNICODE: ON
- language: csharp
@@ -19,10 +20,16 @@ environment:
test: off
install:
- - ps: Start-FileDownload https://googlemock.googlecode.com/files/gmock-1.7.0.zip
- - 7z x gmock-1.7.0.zip
- - rename gmock-1.7.0 gmock
- - ps: Start-FileDownload https://go.microsoft.com/fwlink/?LinkID=809122 -FileName dotnetsdk.exe
+ - 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
+ - curl -L -o dotnetsdk.exe "https://go.microsoft.com/fwlink/?LinkID=809122"
- dotnetsdk.exe /install /quiet /norestart
before_build:
diff --git a/autogen.sh b/autogen.sh
index 5b4c29f8..9f266425 100755
--- a/autogen.sh
+++ b/autogen.sh
@@ -31,10 +31,15 @@ fi
# 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 -O https://googlemock.googlecode.com/files/gmock-1.7.0.zip
- unzip -q gmock-1.7.0.zip
- rm gmock-1.7.0.zip
- mv gmock-1.7.0 gmock
+ 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
+
+ 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
diff --git a/benchmarks/Makefile.am b/benchmarks/Makefile.am
index f730afe5..d98eae5e 100644
--- a/benchmarks/Makefile.am
+++ b/benchmarks/Makefile.am
@@ -16,7 +16,9 @@ benchmarks_protoc_outputs_proto2 = \
benchmark_messages_proto2.pb.cc \
benchmark_messages_proto2.pb.h
-bin_PROGRAMS = generate-datasets
+AM_CXXFLAGS = $(NO_OPT_CXXFLAGS) $(PROTOBUF_OPT_FLAG) -Wall -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare
+
+bin_PROGRAMS = generate-datasets cpp-benchmark
generate_datasets_LDADD = $(top_srcdir)/src/libprotobuf.la
generate_datasets_SOURCES = generate_datasets.cc
@@ -30,6 +32,13 @@ nodist_generate_datasets_SOURCES = \
# 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
+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)
+
$(benchmarks_protoc_outputs): protoc_middleman
$(benchmarks_protoc_outputs_proto2): protoc_middleman2
diff --git a/benchmarks/benchmark_messages_proto2.proto b/benchmarks/benchmark_messages_proto2.proto
index 01f67a1a..59085503 100644
--- a/benchmarks/benchmark_messages_proto2.proto
+++ b/benchmarks/benchmark_messages_proto2.proto
@@ -8,6 +8,8 @@ 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;
diff --git a/benchmarks/benchmark_messages_proto3.proto b/benchmarks/benchmark_messages_proto3.proto
index 32f58698..090b554b 100644
--- a/benchmarks/benchmark_messages_proto3.proto
+++ b/benchmarks/benchmark_messages_proto3.proto
@@ -8,6 +8,8 @@ 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 {
string field1 = 1;
string field9 = 9;
diff --git a/benchmarks/cpp_benchmark.cc b/benchmarks/cpp_benchmark.cc
new file mode 100644
index 00000000..0e6febc2
--- /dev/null
+++ b/benchmarks/cpp_benchmark.cc
@@ -0,0 +1,242 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <glob.h>
+#include <iostream>
+#include <fstream>
+#include "benchmark/benchmark_api.h"
+#include "benchmarks.pb.h"
+#include "benchmark_messages_proto2.pb.h"
+#include "benchmark_messages_proto3.pb.h"
+
+#define PREFIX "dataset."
+#define SUFFIX ".pb"
+
+using benchmarks::BenchmarkDataset;
+using google::protobuf::Arena;
+using google::protobuf::Descriptor;
+using google::protobuf::DescriptorPool;
+using google::protobuf::Message;
+using google::protobuf::MessageFactory;
+
+class Fixture : public benchmark::Fixture {
+ public:
+ Fixture(const BenchmarkDataset& dataset, const std::string& suffix) {
+ for (int i = 0; i < dataset.payload_size(); i++) {
+ payloads_.push_back(dataset.payload(i));
+ }
+
+ const Descriptor* d =
+ DescriptorPool::generated_pool()->FindMessageTypeByName(
+ dataset.message_name());
+
+ if (!d) {
+ std::cerr << "Couldn't find message named '" << dataset.message_name()
+ << "\n";
+ }
+
+ prototype_ = MessageFactory::generated_factory()->GetPrototype(d);
+ SetName((dataset.name() + suffix).c_str());
+ }
+
+ protected:
+ std::vector<std::string> payloads_;
+ const Message* prototype_;
+};
+
+class WrappingCounter {
+ public:
+ WrappingCounter(size_t limit) : value_(0), limit_(limit) {}
+
+ size_t Next() {
+ size_t ret = value_;
+ if (++value_ == limit_) {
+ value_ = 0;
+ }
+ return ret;
+ }
+
+ private:
+ size_t value_;
+ size_t limit_;
+};
+
+template <class T>
+class ParseNewFixture : public Fixture {
+ public:
+ ParseNewFixture(const BenchmarkDataset& dataset)
+ : Fixture(dataset, "_parse_new") {}
+
+ virtual void BenchmarkCase(benchmark::State& state) {
+ WrappingCounter i(payloads_.size());
+ size_t total = 0;
+
+ while (state.KeepRunning()) {
+ T m;
+ const std::string& payload = payloads_[i.Next()];
+ total += payload.size();
+ m.ParseFromString(payload);
+ }
+
+ state.SetBytesProcessed(total);
+ }
+};
+
+template <class T>
+class ParseNewArenaFixture : public Fixture {
+ public:
+ ParseNewArenaFixture(const BenchmarkDataset& dataset)
+ : Fixture(dataset, "_parse_newarena") {}
+
+ virtual void BenchmarkCase(benchmark::State& state) {
+ WrappingCounter i(payloads_.size());
+ size_t total = 0;
+
+ while (state.KeepRunning()) {
+ Arena arena;
+ Message* m = Arena::CreateMessage<T>(&arena);
+ const std::string& payload = payloads_[i.Next()];
+ total += payload.size();
+ m->ParseFromString(payload);
+ }
+
+ state.SetBytesProcessed(total);
+ }
+};
+
+template <class T>
+class ParseReuseFixture : public Fixture {
+ public:
+ ParseReuseFixture(const BenchmarkDataset& dataset)
+ : Fixture(dataset, "_parse_reuse") {}
+
+ virtual void BenchmarkCase(benchmark::State& state) {
+ T m;
+ WrappingCounter i(payloads_.size());
+ size_t total = 0;
+
+ while (state.KeepRunning()) {
+ const std::string& payload = payloads_[i.Next()];
+ total += payload.size();
+ m.ParseFromString(payload);
+ }
+
+ state.SetBytesProcessed(total);
+ }
+};
+
+template <class T>
+class SerializeFixture : public Fixture {
+ public:
+ SerializeFixture(const BenchmarkDataset& dataset)
+ : Fixture(dataset, "_serialize") {
+ for (size_t i = 0; i < payloads_.size(); i++) {
+ message_.push_back(new T);
+ message_.back()->ParseFromString(payloads_[i]);
+ }
+ }
+
+ ~SerializeFixture() {
+ for (size_t i = 0; i < message_.size(); i++) {
+ delete message_[i];
+ }
+ }
+
+ virtual void BenchmarkCase(benchmark::State& state) {
+ size_t total = 0;
+ std::string str;
+ WrappingCounter i(payloads_.size());
+
+ while (state.KeepRunning()) {
+ str.clear();
+ message_[i.Next()]->SerializeToString(&str);
+ total += str.size();
+ }
+
+ state.SetBytesProcessed(total);
+ }
+
+ private:
+ std::vector<T*> message_;
+};
+
+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>());
+}
+
+template <class T>
+void RegisterBenchmarksForType(const BenchmarkDataset& dataset) {
+ ::benchmark::internal::RegisterBenchmarkInternal(
+ new ParseNewFixture<T>(dataset));
+ ::benchmark::internal::RegisterBenchmarkInternal(
+ new ParseReuseFixture<T>(dataset));
+ ::benchmark::internal::RegisterBenchmarkInternal(
+ new ParseNewArenaFixture<T>(dataset));
+ ::benchmark::internal::RegisterBenchmarkInternal(
+ new SerializeFixture<T>(dataset));
+}
+
+void RegisterBenchmarks(const std::string& dataset_bytes) {
+ BenchmarkDataset dataset;
+ GOOGLE_CHECK(dataset.ParseFromString(dataset_bytes));
+
+ if (dataset.message_name() == "benchmarks.proto3.GoogleMessage1") {
+ RegisterBenchmarksForType<benchmarks::proto3::GoogleMessage1>(dataset);
+ } else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage1") {
+ RegisterBenchmarksForType<benchmarks::proto2::GoogleMessage1>(dataset);
+ } else if (dataset.message_name() == "benchmarks.proto2.GoogleMessage2") {
+ RegisterBenchmarksForType<benchmarks::proto2::GoogleMessage2>(dataset);
+ } else {
+ std::cerr << "Unknown message type: " << dataset.message_name();
+ exit(1);
+ }
+}
+
+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");
+ return 1;
+ }
+
+ 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/readme.txt b/benchmarks/readme.txt
index 2c836d0a..b08b8bc0 100644
--- a/benchmarks/readme.txt
+++ b/benchmarks/readme.txt
@@ -22,29 +22,25 @@ Running a benchmark (Java)
$ 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 google_speed.proto
+ $ protoc --java_out=tmp google_size.proto
4) Build the generated code, e.g.
- $ cd tmp
- $ javac -d . -cp ../protobuf.jar benchmarks/*.java
+ $ 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 .;../protobuf.jar com.google.protocolbuffers.ProtoBench
- benchmarks.GoogleSize$SizeMessage1 ../google_message1.dat
- benchmarks.GoogleSpeed$SpeedMessage1 ../google_message1.dat
- benchmarks.GoogleSize$SizeMessage2 ../google_message2.dat
- benchmarks.GoogleSpeed$SpeedMessage2 ../google_message2.dat
+ $ 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 6 tests
+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 12 minutes to run.
+ about 8 minutes to run.
Benchmarks available
--------------------
From Google:
-google_size.proto and google_speed.proto, messages
-google_message1.dat and google_message2.dat. The proto files are
-equivalent, but optimized differently.
+google_size.proto,
+messages google_message1.dat and google_message2.dat.
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt
index 07b176d9..df3b2012 100644
--- a/cmake/CMakeLists.txt
+++ b/cmake/CMakeLists.txt
@@ -86,6 +86,7 @@ if (CMAKE_USE_PTHREADS_INIT)
add_definitions(-DHAVE_PTHREAD)
endif (CMAKE_USE_PTHREADS_INIT)
+set(_protobuf_FIND_ZLIB)
if (protobuf_WITH_ZLIB)
find_package(ZLIB)
if (ZLIB_FOUND)
@@ -96,6 +97,7 @@ if (protobuf_WITH_ZLIB)
# Using imported target if exists
if (TARGET ZLIB::ZLIB)
set(ZLIB_LIBRARIES ZLIB::ZLIB)
+ set(_protobuf_FIND_ZLIB "if(NOT ZLIB_FOUND)\n find_package(ZLIB)\nendif()")
endif (TARGET ZLIB::ZLIB)
else (ZLIB_FOUND)
set(HAVE_ZLIB 0)
@@ -157,6 +159,10 @@ else (MSVC)
set(LIB_PREFIX)
endif (MSVC)
+if (protobuf_UNICODE)
+ add_definitions(-DUNICODE -D_UNICODE)
+endif (protobuf_UNICODE)
+
include(libprotobuf-lite.cmake)
include(libprotobuf.cmake)
include(libprotoc.cmake)
diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in
index 9edafca8..4b572bb6 100644
--- a/cmake/extract_includes.bat.in
+++ b/cmake/extract_includes.bat.in
@@ -8,6 +8,7 @@ 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
mkdir include\google\protobuf\compiler\python
mkdir include\google\protobuf\compiler\ruby
mkdir include\google\protobuf\io
@@ -23,7 +24,6 @@ copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\command_line_
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_generator.h include\google\protobuf\compiler\cpp\cpp_generator.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_generator.h include\google\protobuf\compiler\csharp\csharp_generator.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_names.h include\google\protobuf\compiler\csharp\csharp_names.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_options.h include\google\protobuf\compiler\csharp\csharp_options.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h include\google\protobuf\compiler\importer.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h include\google\protobuf\compiler\java\java_generator.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h include\google\protobuf\compiler\java\java_names.h
@@ -32,6 +32,7 @@ copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generat
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h include\google\protobuf\compiler\objectivec\objectivec_generator.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_helpers.h include\google\protobuf\compiler\objectivec\objectivec_helpers.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\parser.h include\google\protobuf\compiler\parser.h
+copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\php\php_generator.h include\google\protobuf\compiler\php\php_generator.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.h include\google\protobuf\compiler\plugin.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.pb.h include\google\protobuf\compiler\plugin.pb.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\python_generator.h include\google\protobuf\compiler\python\python_generator.h
@@ -48,6 +49,7 @@ copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_reflect
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_enum_util.h include\google\protobuf\generated_enum_util.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_reflection.h include\google\protobuf\generated_message_reflection.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\generated_message_util.h include\google\protobuf\generated_message_util.h
+copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\has_bits.h include\google\protobuf\has_bits.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\coded_stream.h include\google\protobuf\io\coded_stream.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\gzip_stream.h include\google\protobuf\io\gzip_stream.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\io\printer.h include\google\protobuf\io\printer.h
@@ -78,11 +80,12 @@ copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_intern
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_gcc.h include\google\protobuf\stubs\atomicops_internals_arm_gcc.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_arm_qnx.h include\google\protobuf\stubs\atomicops_internals_arm_qnx.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_atomicword_compat.h include\google\protobuf\stubs\atomicops_internals_atomicword_compat.h
+copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h include\google\protobuf\stubs\atomicops_internals_generic_c11_atomic.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_generic_gcc.h include\google\protobuf\stubs\atomicops_internals_generic_gcc.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_macosx.h include\google\protobuf\stubs\atomicops_internals_macosx.h
copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_mips_gcc.h include\google\protobuf\stubs\atomicops_internals_mips_gcc.h
-copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\stubs\atomicops_internals_pnacl.h include\google\protobuf\stubs\atomicops_internals_pnacl.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
diff --git a/cmake/install.cmake b/cmake/install.cmake
index 94ef2198..73e31984 100644
--- a/cmake/install.cmake
+++ b/cmake/install.cmake
@@ -110,7 +110,7 @@ install(EXPORT protobuf-targets
NAMESPACE protobuf::
COMPONENT protobuf-export)
-install(DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_CMAKEDIR}/
+install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_CMAKEDIR}/
DESTINATION "${CMAKE_INSTALL_CMAKEDIR}"
COMPONENT protobuf-export
PATTERN protobuf-targets.cmake EXCLUDE
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake
index 8930c1ca..26e1f356 100644
--- a/cmake/libprotobuf.cmake
+++ b/cmake/libprotobuf.cmake
@@ -56,7 +56,10 @@ set(libprotobuf_files
add_library(libprotobuf ${protobuf_SHARED_OR_STATIC}
${libprotobuf_lite_files} ${libprotobuf_files})
-target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT} ${ZLIB_LIBRARIES})
+target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT})
+if(protobuf_WITH_ZLIB)
+ target_link_libraries(libprotobuf ${ZLIB_LIBRARIES})
+endif()
target_include_directories(libprotobuf PUBLIC ${protobuf_source_dir}/src)
if(MSVC AND protobuf_BUILD_SHARED_LIBS)
target_compile_definitions(libprotobuf
diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake
index 8df8986a..71c3494c 100644
--- a/cmake/libprotoc.cmake
+++ b/cmake/libprotoc.cmake
@@ -84,6 +84,7 @@ set(libprotoc_files
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc
+ ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.cc
${protobuf_source_dir}/src/google/protobuf/compiler/plugin.cc
${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.cc
${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.cc
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in
index 37315510..a044fe5c 100644
--- a/cmake/protobuf-config.cmake.in
+++ b/cmake/protobuf-config.cmake.in
@@ -1,6 +1,9 @@
# User options
include("${CMAKE_CURRENT_LIST_DIR}/protobuf-options.cmake")
+# Depend packages
+@_protobuf_FIND_ZLIB@
+
# Imported targets
include("${CMAKE_CURRENT_LIST_DIR}/protobuf-targets.cmake")
diff --git a/cmake/protobuf-module.cmake.in b/cmake/protobuf-module.cmake.in
index 6e0bcf90..614e4c04 100644
--- a/cmake/protobuf-module.cmake.in
+++ b/cmake/protobuf-module.cmake.in
@@ -147,7 +147,6 @@ function(_protobuf_find_libraries name filename)
LOCATION_RELEASE)
get_target_property(${name}_LIBRARY_DEBUG protobuf::lib${filename}
LOCATION_DEBUG)
- endif()
select_library_configurations(${name})
set(${name}_LIBRARY ${${name}_LIBRARY} PARENT_SCOPE)
diff --git a/cmake/tests.cmake b/cmake/tests.cmake
index ec0d6030..30214e7d 100644
--- a/cmake/tests.cmake
+++ b/cmake/tests.cmake
@@ -63,8 +63,10 @@ set(tests_protos
google/protobuf/util/internal/testdata/field_mask.proto
google/protobuf/util/internal/testdata/maps.proto
google/protobuf/util/internal/testdata/oneofs.proto
+ google/protobuf/util/internal/testdata/proto3.proto
google/protobuf/util/internal/testdata/struct.proto
google/protobuf/util/internal/testdata/timestamp_duration.proto
+ google/protobuf/util/internal/testdata/wrappers.proto
google/protobuf/util/json_format_proto3.proto
google/protobuf/util/message_differencer_unittest.proto
)
diff --git a/composer.json b/composer.json
new file mode 100644
index 00000000..6afe71ce
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,23 @@
+{
+ "name": "google/protobuf",
+ "type": "library",
+ "description": "proto library for PHP",
+ "keywords": ["proto"],
+ "homepage": "https://developers.google.com/protocol-buffers/",
+ "license": "BSD-3-Clause",
+ "require": {
+ "php": ">=5.5.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": ">=4.8.0"
+ },
+ "autoload": {
+ "psr-4": {
+ "Google\\": "php/src/Google"
+ },
+ "files": [
+ "php/src/Google/Protobuf/descriptor.php",
+ "php/src/Google/Protobuf/descriptor_internal.pb.php"
+ ]
+ }
+}
diff --git a/configure.ac b/configure.ac
index 41887997..896f3471 100644
--- a/configure.ac
+++ b/configure.ac
@@ -17,7 +17,7 @@ AC_PREREQ(2.59)
# In the SVN trunk, the version should always be the next anticipated release
# version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed
# the size of one file name in the dist tarfile over the 99-char limit.)
-AC_INIT([Protocol Buffers],[3.0.0],[protobuf@googlegroups.com],[protobuf])
+AC_INIT([Protocol Buffers],[3.1.0],[protobuf@googlegroups.com],[protobuf])
AM_MAINTAINER_MODE([enable])
@@ -31,7 +31,7 @@ AC_CONFIG_MACRO_DIR([m4])
AC_ARG_VAR(DIST_LANG, [language to include in the distribution package (i.e., make dist)])
case "$DIST_LANG" in
"") DIST_LANG=all ;;
- all | cpp | csharp | java | python | javanano | objectivec | ruby | js) ;;
+ all | cpp | csharp | java | python | javanano | objectivec | ruby | js | php) ;;
*) AC_MSG_FAILURE([unknown language: $DIST_LANG]) ;;
esac
AC_SUBST(DIST_LANG)
diff --git a/conformance/Makefile.am b/conformance/Makefile.am
index b76407ee..5985e1d9 100644
--- a/conformance/Makefile.am
+++ b/conformance/Makefile.am
@@ -20,7 +20,7 @@ other_language_protoc_outputs = \
conformance_pb2.py \
Conformance.pbobjc.h \
Conformance.pbobjc.m \
- conformance.rb \
+ conformance_pb.rb \
com/google/protobuf/Any.java \
com/google/protobuf/AnyOrBuilder.java \
com/google/protobuf/AnyProto.java \
@@ -251,31 +251,31 @@ conformance-csharp: $(other_language_protoc_outputs)
# Targets for actually running tests.
test_cpp: protoc_middleman conformance-test-runner conformance-cpp
- ./conformance-test-runner --failure_list failure_list_cpp.txt ./conformance-cpp
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_cpp.txt ./conformance-cpp
test_java: protoc_middleman conformance-test-runner conformance-java
- ./conformance-test-runner --failure_list failure_list_java.txt ./conformance-java
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_java.txt ./conformance-java
test_java_lite: protoc_middleman conformance-test-runner conformance-java-lite
- ./conformance-test-runner ./conformance-java-lite
+ ./conformance-test-runner --enforce_recommended ./conformance-java-lite
test_csharp: protoc_middleman conformance-test-runner conformance-csharp
- ./conformance-test-runner --failure_list failure_list_csharp.txt ./conformance-csharp
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_csharp.txt ./conformance-csharp
test_ruby: protoc_middleman conformance-test-runner $(other_language_protoc_outputs)
- RUBYLIB=../ruby/lib:. ./conformance-test-runner --failure_list failure_list_ruby.txt ./conformance_ruby.rb
+ RUBYLIB=../ruby/lib:. ./conformance-test-runner --enforce_recommended --failure_list failure_list_ruby.txt ./conformance_ruby.rb
# These depend on library paths being properly set up. The easiest way to
# run them is to just use "tox" from the python dir.
test_python: protoc_middleman conformance-test-runner
- ./conformance-test-runner --failure_list failure_list_python.txt ./conformance_python.py
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_python.txt ./conformance_python.py
test_python_cpp: protoc_middleman conformance-test-runner
- ./conformance-test-runner --failure_list failure_list_python_cpp.txt ./conformance_python.py
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_python_cpp.txt ./conformance_python.py
if OBJC_CONFORMANCE_TEST
test_objc: protoc_middleman conformance-test-runner conformance-objc
- ./conformance-test-runner --failure_list failure_list_objc.txt ./conformance-objc
+ ./conformance-test-runner --enforce_recommended --failure_list failure_list_objc.txt ./conformance-objc
endif
diff --git a/conformance/conformance.proto b/conformance/conformance.proto
index fc96074a..95a8fd13 100644
--- a/conformance/conformance.proto
+++ b/conformance/conformance.proto
@@ -210,6 +210,11 @@ message TestAllTypes {
NestedMessage oneof_nested_message = 112;
string oneof_string = 113;
bytes oneof_bytes = 114;
+ bool oneof_bool = 115;
+ uint64 oneof_uint64 = 116;
+ float oneof_float = 117;
+ double oneof_double = 118;
+ NestedEnum oneof_enum = 119;
}
// Well-known types
@@ -248,6 +253,7 @@ message TestAllTypes {
repeated google.protobuf.Value repeated_value = 316;
// Test field-name-to-JSON-name convention.
+ // (protobuf says names can be any valid C/C++ identifier.)
int32 fieldname1 = 401;
int32 field_name2 = 402;
int32 _field_name3 = 403;
@@ -260,6 +266,12 @@ message TestAllTypes {
int32 Field_Name10 = 410;
int32 FIELD_NAME11 = 411;
int32 FIELD_name12 = 412;
+ int32 __field_name13 = 413;
+ int32 __Field_name14 = 414;
+ int32 field__name15 = 415;
+ int32 field__Name16 = 416;
+ int32 field_name17__ = 417;
+ int32 Field_name18__ = 418;
}
message ForeignMessage {
diff --git a/conformance/conformance_python.py b/conformance/conformance_python.py
index a490c8e8..2f4a7812 100755
--- a/conformance/conformance_python.py
+++ b/conformance/conformance_python.py
@@ -67,7 +67,7 @@ def do_test(request):
elif request.WhichOneof('payload') == 'json_payload':
try:
json_format.Parse(request.json_payload, test_message)
- except json_format.ParseError as e:
+ except Exception as e:
response.parse_error = str(e)
return response
@@ -81,7 +81,11 @@ def do_test(request):
response.protobuf_payload = test_message.SerializeToString()
elif request.requested_output_format == conformance_pb2.JSON:
- response.json_payload = json_format.MessageToJson(test_message)
+ try:
+ response.json_payload = json_format.MessageToJson(test_message)
+ except Exception as e:
+ response.serialize_error = str(e)
+ return response
except Exception as e:
response.runtime_error = str(e)
diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc
index 598ef732..b74122c6 100644
--- a/conformance/conformance_test.cc
+++ b/conformance/conformance_test.cc
@@ -183,6 +183,7 @@ void ConformanceTestSuite::ReportSuccess(const string& test_name) {
}
void ConformanceTestSuite::ReportFailure(const string& test_name,
+ ConformanceLevel level,
const ConformanceRequest& request,
const ConformanceResponse& response,
const char* fmt, ...) {
@@ -190,6 +191,8 @@ void ConformanceTestSuite::ReportFailure(const string& test_name,
expected_failures_++;
if (!verbose_)
return;
+ } else if (level == RECOMMENDED && !enforce_recommended_) {
+ StringAppendF(&output_, "WARNING, test=%s: ", test_name.c_str());
} else {
StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
unexpected_failing_tests_.insert(test_name);
@@ -214,6 +217,15 @@ void ConformanceTestSuite::ReportSkip(const string& test_name,
skipped_.insert(test_name);
}
+string ConformanceTestSuite::ConformanceLevelToString(ConformanceLevel level) {
+ switch (level) {
+ case REQUIRED: return "Required";
+ case RECOMMENDED: return "Recommended";
+ }
+ GOOGLE_LOG(FATAL) << "Unknown value: " << level;
+ return "";
+}
+
void ConformanceTestSuite::RunTest(const string& test_name,
const ConformanceRequest& request,
ConformanceResponse* response) {
@@ -241,8 +253,9 @@ void ConformanceTestSuite::RunTest(const string& test_name,
}
void ConformanceTestSuite::RunValidInputTest(
- const string& test_name, const string& input, WireFormat input_format,
- const string& equivalent_text_format, WireFormat requested_output) {
+ const string& test_name, ConformanceLevel level, const string& input,
+ WireFormat input_format, const string& equivalent_text_format,
+ WireFormat requested_output) {
TestAllTypes reference_message;
GOOGLE_CHECK(
TextFormat::ParseFromString(equivalent_text_format, &reference_message))
@@ -272,11 +285,16 @@ void ConformanceTestSuite::RunValidInputTest(
TestAllTypes test_message;
switch (response.result_case()) {
+ case ConformanceResponse::RESULT_NOT_SET:
+ ReportFailure(test_name, level, request, response,
+ "Response didn't have any field in the Response.");
+ return;
+
case ConformanceResponse::kParseError:
case ConformanceResponse::kRuntimeError:
case ConformanceResponse::kSerializeError:
- ReportFailure(test_name, request, response,
- "Failed to parse JSON input or produce JSON output.");
+ ReportFailure(test_name, level, request, response,
+ "Failed to parse input or produce output.");
return;
case ConformanceResponse::kSkipped:
@@ -286,7 +304,7 @@ void ConformanceTestSuite::RunValidInputTest(
case ConformanceResponse::kJsonPayload: {
if (requested_output != conformance::JSON) {
ReportFailure(
- test_name, request, response,
+ test_name, level, request, response,
"Test was asked for protobuf output but provided JSON instead.");
return;
}
@@ -295,13 +313,13 @@ void ConformanceTestSuite::RunValidInputTest(
JsonToBinaryString(type_resolver_.get(), type_url_,
response.json_payload(), &binary_protobuf);
if (!status.ok()) {
- ReportFailure(test_name, request, response,
+ ReportFailure(test_name, level, request, response,
"JSON output we received from test was unparseable.");
return;
}
if (!test_message.ParseFromString(binary_protobuf)) {
- ReportFailure(test_name, request, response,
+ ReportFailure(test_name, level, request, response,
"INTERNAL ERROR: internal JSON->protobuf transcode "
"yielded unparseable proto.");
return;
@@ -313,13 +331,13 @@ void ConformanceTestSuite::RunValidInputTest(
case ConformanceResponse::kProtobufPayload: {
if (requested_output != conformance::PROTOBUF) {
ReportFailure(
- test_name, request, response,
+ test_name, level, request, response,
"Test was asked for JSON output but provided protobuf instead.");
return;
}
if (!test_message.ParseFromString(response.protobuf_payload())) {
- ReportFailure(test_name, request, response,
+ ReportFailure(test_name, level, request, response,
"Protobuf output we received from test was unparseable.");
return;
}
@@ -342,7 +360,7 @@ void ConformanceTestSuite::RunValidInputTest(
if (differencer.Compare(reference_message, test_message)) {
ReportSuccess(test_name);
} else {
- ReportFailure(test_name, request, response,
+ ReportFailure(test_name, level, request, response,
"Output was not equivalent to reference message: %s.",
differences.c_str());
}
@@ -350,11 +368,12 @@ void ConformanceTestSuite::RunValidInputTest(
// Expect that this precise protobuf will cause a parse error.
void ConformanceTestSuite::ExpectParseFailureForProto(
- const string& proto, const string& test_name) {
+ const string& proto, const string& test_name, ConformanceLevel level) {
ConformanceRequest request;
ConformanceResponse response;
request.set_protobuf_payload(proto);
- string effective_test_name = "ProtobufInput." + test_name;
+ string effective_test_name = ConformanceLevelToString(level) +
+ ".ProtobufInput." + test_name;
// We don't expect output, but if the program erroneously accepts the protobuf
// we let it send its response as this. We must not leave it unspecified.
@@ -366,7 +385,7 @@ void ConformanceTestSuite::ExpectParseFailureForProto(
} else if (response.result_case() == ConformanceResponse::kSkipped) {
ReportSkip(effective_test_name, request, response);
} else {
- ReportFailure(effective_test_name, request, response,
+ ReportFailure(effective_test_name, level, request, response,
"Should have failed to parse, but didn't.");
}
}
@@ -377,25 +396,39 @@ void ConformanceTestSuite::ExpectParseFailureForProto(
//
// TODO(haberman): implement the second of these.
void ConformanceTestSuite::ExpectHardParseFailureForProto(
- const string& proto, const string& test_name) {
- return ExpectParseFailureForProto(proto, test_name);
+ const string& proto, const string& test_name, ConformanceLevel level) {
+ return ExpectParseFailureForProto(proto, test_name, level);
}
void ConformanceTestSuite::RunValidJsonTest(
- const string& test_name, const string& input_json,
+ const string& test_name, ConformanceLevel level, const string& input_json,
const string& equivalent_text_format) {
- RunValidInputTest("JsonInput." + test_name + ".ProtobufOutput", input_json,
- conformance::JSON, equivalent_text_format,
- conformance::PROTOBUF);
- RunValidInputTest("JsonInput." + test_name + ".JsonOutput", input_json,
- conformance::JSON, equivalent_text_format,
- conformance::JSON);
+ RunValidInputTest(
+ ConformanceLevelToString(level) + ".JsonInput." + test_name +
+ ".ProtobufOutput", level, input_json, conformance::JSON,
+ equivalent_text_format, conformance::PROTOBUF);
+ RunValidInputTest(
+ ConformanceLevelToString(level) + ".JsonInput." + test_name +
+ ".JsonOutput", level, input_json, conformance::JSON,
+ equivalent_text_format, conformance::JSON);
}
void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
- const string& test_name, const TestAllTypes& input,
+ const string& test_name, ConformanceLevel level, const TestAllTypes& input,
+ const string& equivalent_text_format) {
+ RunValidInputTest(
+ ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
+ ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
+ equivalent_text_format, conformance::JSON);
+}
+
+void ConformanceTestSuite::RunValidProtobufTest(
+ const string& test_name, ConformanceLevel level, const TestAllTypes& input,
const string& equivalent_text_format) {
- RunValidInputTest("ProtobufInput." + test_name + ".JsonOutput",
+ RunValidInputTest("ProtobufInput." + test_name + ".ProtobufOutput", level,
+ input.SerializeAsString(), conformance::PROTOBUF,
+ equivalent_text_format, conformance::PROTOBUF);
+ RunValidInputTest("ProtobufInput." + test_name + ".JsonOutput", level,
input.SerializeAsString(), conformance::PROTOBUF,
equivalent_text_format, conformance::JSON);
}
@@ -406,14 +439,15 @@ void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
// method allows strict checking on a proto3 JSON serializer by inspecting
// the JSON output directly.
void ConformanceTestSuite::RunValidJsonTestWithValidator(
- const string& test_name, const string& input_json,
+ const string& test_name, ConformanceLevel level, const string& input_json,
const Validator& validator) {
ConformanceRequest request;
ConformanceResponse response;
request.set_json_payload(input_json);
request.set_requested_output_format(conformance::JSON);
- string effective_test_name = "JsonInput." + test_name + ".Validator";
+ string effective_test_name = ConformanceLevelToString(level) +
+ ".JsonInput." + test_name + ".Validator";
RunTest(effective_test_name, request, &response);
@@ -423,7 +457,7 @@ void ConformanceTestSuite::RunValidJsonTestWithValidator(
}
if (response.result_case() != ConformanceResponse::kJsonPayload) {
- ReportFailure(effective_test_name, request, response,
+ ReportFailure(effective_test_name, level, request, response,
"Expected JSON payload but got type %d.",
response.result_case());
return;
@@ -431,13 +465,13 @@ void ConformanceTestSuite::RunValidJsonTestWithValidator(
Json::Reader reader;
Json::Value value;
if (!reader.parse(response.json_payload(), value)) {
- ReportFailure(effective_test_name, request, response,
+ ReportFailure(effective_test_name, level, request, response,
"JSON payload cannot be parsed as valid JSON: %s",
reader.getFormattedErrorMessages().c_str());
return;
}
if (!validator(value)) {
- ReportFailure(effective_test_name, request, response,
+ ReportFailure(effective_test_name, level, request, response,
"JSON payload validation failed.");
return;
}
@@ -445,11 +479,12 @@ void ConformanceTestSuite::RunValidJsonTestWithValidator(
}
void ConformanceTestSuite::ExpectParseFailureForJson(
- const string& test_name, const string& input_json) {
+ const string& test_name, ConformanceLevel level, const string& input_json) {
ConformanceRequest request;
ConformanceResponse response;
request.set_json_payload(input_json);
- string effective_test_name = "JsonInput." + test_name;
+ string effective_test_name =
+ ConformanceLevelToString(level) + ".JsonInput." + test_name;
// We don't expect output, but if the program erroneously accepts the protobuf
// we let it send its response as this. We must not leave it unspecified.
@@ -461,13 +496,13 @@ void ConformanceTestSuite::ExpectParseFailureForJson(
} else if (response.result_case() == ConformanceResponse::kSkipped) {
ReportSkip(effective_test_name, request, response);
} else {
- ReportFailure(effective_test_name, request, response,
+ ReportFailure(effective_test_name, level, request, response,
"Should have failed to parse, but didn't.");
}
}
void ConformanceTestSuite::ExpectSerializeFailureForJson(
- const string& test_name, const string& text_format) {
+ const string& test_name, ConformanceLevel level, const string& text_format) {
TestAllTypes payload_message;
GOOGLE_CHECK(
TextFormat::ParseFromString(text_format, &payload_message))
@@ -476,7 +511,8 @@ void ConformanceTestSuite::ExpectSerializeFailureForJson(
ConformanceRequest request;
ConformanceResponse response;
request.set_protobuf_payload(payload_message.SerializeAsString());
- string effective_test_name = test_name + ".JsonOutput";
+ string effective_test_name =
+ ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
request.set_requested_output_format(conformance::JSON);
RunTest(effective_test_name, request, &response);
@@ -485,7 +521,7 @@ void ConformanceTestSuite::ExpectSerializeFailureForJson(
} else if (response.result_case() == ConformanceResponse::kSkipped) {
ReportSkip(effective_test_name, request, response);
} else {
- ReportFailure(effective_test_name, request, response,
+ ReportFailure(effective_test_name, level, request, response,
"Should have failed to serialize, but didn't.");
}
}
@@ -511,41 +547,43 @@ void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
ExpectParseFailureForProto(
tag(fieldnum, wire_type),
- "PrematureEofBeforeKnownNonRepeatedValue" + type_name);
+ "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
ExpectParseFailureForProto(
tag(rep_fieldnum, wire_type),
- "PrematureEofBeforeKnownRepeatedValue" + type_name);
+ "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
ExpectParseFailureForProto(
tag(UNKNOWN_FIELD, wire_type),
- "PrematureEofBeforeUnknownValue" + type_name);
+ "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
ExpectParseFailureForProto(
cat( tag(fieldnum, wire_type), incomplete ),
- "PrematureEofInsideKnownNonRepeatedValue" + type_name);
+ "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
ExpectParseFailureForProto(
cat( tag(rep_fieldnum, wire_type), incomplete ),
- "PrematureEofInsideKnownRepeatedValue" + type_name);
+ "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
ExpectParseFailureForProto(
cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
- "PrematureEofInsideUnknownValue" + type_name);
+ "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
ExpectParseFailureForProto(
cat( tag(fieldnum, wire_type), varint(1) ),
- "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name);
+ "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
+ REQUIRED);
ExpectParseFailureForProto(
cat( tag(rep_fieldnum, wire_type), varint(1) ),
- "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name);
+ "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
+ REQUIRED);
// EOF in the middle of delimited data for unknown value.
ExpectParseFailureForProto(
cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
- "PrematureEofInDelimitedDataForUnknownValue" + type_name);
+ "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
if (type == FieldDescriptor::TYPE_MESSAGE) {
// Submessage ends in the middle of a value.
@@ -556,7 +594,7 @@ void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
cat( tag(fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
varint(incomplete_submsg.size()),
incomplete_submsg ),
- "PrematureEofInSubmessageValue" + type_name);
+ "PrematureEofInSubmessageValue" + type_name, REQUIRED);
}
} else if (type != FieldDescriptor::TYPE_GROUP) {
// Non-delimited, non-group: eligible for packing.
@@ -566,13 +604,13 @@ void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
varint(incomplete.size()),
incomplete ),
- "PrematureEofInPackedFieldValue" + type_name);
+ "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
// EOF in the middle of packed region.
ExpectParseFailureForProto(
cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
varint(1) ),
- "PrematureEofInPackedField" + type_name);
+ "PrematureEofInPackedField" + type_name, REQUIRED);
}
}
@@ -635,24 +673,29 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
}
- RunValidJsonTest("HelloWorld", "{\"optionalString\":\"Hello, World!\"}",
+ RunValidJsonTest("HelloWorld", REQUIRED,
+ "{\"optionalString\":\"Hello, World!\"}",
"optional_string: 'Hello, World!'");
+ // NOTE: The spec for JSON support is still being sorted out, these may not
+ // all be correct.
// Test field name conventions.
RunValidJsonTest(
- "FieldNameInSnakeCase",
+ "FieldNameInSnakeCase", REQUIRED,
R"({
"fieldname1": 1,
"fieldName2": 2,
- "FieldName3": 3
+ "fieldName3": 3,
+ "fieldName4": 4
})",
R"(
fieldname1: 1
field_name2: 2
_field_name3: 3
+ field__name4_: 4
)");
RunValidJsonTest(
- "FieldNameWithNumbers",
+ "FieldNameWithNumbers", REQUIRED,
R"({
"field0name5": 5,
"field0Name6": 6
@@ -662,14 +705,14 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
field_0_name6: 6
)");
RunValidJsonTest(
- "FieldNameWithMixedCases",
+ "FieldNameWithMixedCases", REQUIRED,
R"({
"fieldName7": 7,
- "fieldName8": 8,
+ "FieldName8": 8,
"fieldName9": 9,
- "fieldName10": 10,
- "fIELDNAME11": 11,
- "fIELDName12": 12
+ "FieldName10": 10,
+ "FIELDNAME11": 11,
+ "FIELDName12": 12
})",
R"(
fieldName7: 7
@@ -679,13 +722,32 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
FIELD_NAME11: 11
FIELD_name12: 12
)");
+ RunValidJsonTest(
+ "FieldNameWithDoubleUnderscores", RECOMMENDED,
+ R"({
+ "fieldName13": 13,
+ "fieldName14": 14,
+ "fieldName15": 15,
+ "fieldName16": 16,
+ "fieldName17": 17,
+ "fieldName18": 18
+ })",
+ R"(
+ __field_name13: 13
+ __Field_name14: 14
+ field__name15: 15
+ field__Name16: 16
+ field_name17__: 17
+ Field_name18__: 18
+ )");
// Using the original proto field name in JSON is also allowed.
RunValidJsonTest(
- "OriginalProtoFieldName",
+ "OriginalProtoFieldName", REQUIRED,
R"({
"fieldname1": 1,
"field_name2": 2,
"_field_name3": 3,
+ "field__name4_": 4,
"field0name5": 5,
"field_0_name6": 6,
"fieldName7": 7,
@@ -693,12 +755,19 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"field_Name9": 9,
"Field_Name10": 10,
"FIELD_NAME11": 11,
- "FIELD_name12": 12
+ "FIELD_name12": 12,
+ "__field_name13": 13,
+ "__Field_name14": 14,
+ "field__name15": 15,
+ "field__Name16": 16,
+ "field_name17__": 17,
+ "Field_name18__": 18
})",
R"(
fieldname1: 1
field_name2: 2
_field_name3: 3
+ field__name4_: 4
field0name5: 5
field_0_name6: 6
fieldName7: 7
@@ -707,61 +776,122 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
Field_Name10: 10
FIELD_NAME11: 11
FIELD_name12: 12
+ __field_name13: 13
+ __Field_name14: 14
+ field__name15: 15
+ field__Name16: 16
+ field_name17__: 17
+ Field_name18__: 18
)");
// Field names can be escaped.
RunValidJsonTest(
- "FieldNameEscaped",
+ "FieldNameEscaped", REQUIRED,
R"({"fieldn\u0061me1": 1})",
"fieldname1: 1");
+ // String ends with escape character.
+ ExpectParseFailureForJson(
+ "StringEndsWithEscapeChar", RECOMMENDED,
+ "{\"optionalString\": \"abc\\");
// Field names must be quoted (or it's not valid JSON).
ExpectParseFailureForJson(
- "FieldNameNotQuoted",
+ "FieldNameNotQuoted", RECOMMENDED,
"{fieldname1: 1}");
// Trailing comma is not allowed (not valid JSON).
ExpectParseFailureForJson(
- "TrailingCommaInAnObject",
+ "TrailingCommaInAnObject", RECOMMENDED,
R"({"fieldname1":1,})");
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
+ R"({"fieldname1":1 ,})");
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
+ R"({"fieldname1":1 , })");
+ ExpectParseFailureForJson(
+ "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
+ R"({
+ "fieldname1":1,
+ })");
// JSON doesn't support comments.
ExpectParseFailureForJson(
- "JsonWithComments",
+ "JsonWithComments", RECOMMENDED,
R"({
// This is a comment.
"fieldname1": 1
})");
+ // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
+ RunValidJsonTest(
+ "OneLineNoSpaces", RECOMMENDED,
+ "{\"optionalInt32\":1,\"optionalInt64\":2}",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ RunValidJsonTest(
+ "OneLineWithSpaces", RECOMMENDED,
+ "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ RunValidJsonTest(
+ "MultilineNoSpaces", RECOMMENDED,
+ "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ RunValidJsonTest(
+ "MultilineWithSpaces", RECOMMENDED,
+ "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
+ R"(
+ optional_int32: 1
+ optional_int64: 2
+ )");
+ // Missing comma between key/value pairs.
+ ExpectParseFailureForJson(
+ "MissingCommaOneLine", RECOMMENDED,
+ "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
+ ExpectParseFailureForJson(
+ "MissingCommaMultiline", RECOMMENDED,
+ "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
// Duplicated field names are not allowed.
ExpectParseFailureForJson(
- "FieldNameDuplicate",
+ "FieldNameDuplicate", RECOMMENDED,
R"({
"optionalNestedMessage": {a: 1},
"optionalNestedMessage": {}
})");
ExpectParseFailureForJson(
- "FieldNameDuplicateDifferentCasing1",
+ "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
R"({
"optional_nested_message": {a: 1},
"optionalNestedMessage": {}
})");
ExpectParseFailureForJson(
- "FieldNameDuplicateDifferentCasing2",
+ "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
R"({
"optionalNestedMessage": {a: 1},
"optional_nested_message": {}
})");
+ // NOTE: The spec for JSON support is still being sorted out, these may not
+ // all be correct.
// Serializers should use lowerCamelCase by default.
RunValidJsonTestWithValidator(
- "FieldNameInLowerCamelCase",
+ "FieldNameInLowerCamelCase", REQUIRED,
R"({
"fieldname1": 1,
"fieldName2": 2,
- "FieldName3": 3
+ "fieldName3": 3,
+ "fieldName4": 4
})",
[](const Json::Value& value) {
return value.isMember("fieldname1") &&
value.isMember("fieldName2") &&
- value.isMember("FieldName3");
+ value.isMember("fieldName3") &&
+ value.isMember("fieldName4");
});
RunValidJsonTestWithValidator(
- "FieldNameWithNumbers",
+ "FieldNameWithNumbers", REQUIRED,
R"({
"field0name5": 5,
"field0Name6": 6
@@ -771,47 +901,65 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
value.isMember("field0Name6");
});
RunValidJsonTestWithValidator(
- "FieldNameWithMixedCases",
+ "FieldNameWithMixedCases", REQUIRED,
R"({
"fieldName7": 7,
- "fieldName8": 8,
+ "FieldName8": 8,
"fieldName9": 9,
- "fieldName10": 10,
- "fIELDNAME11": 11,
- "fIELDName12": 12
+ "FieldName10": 10,
+ "FIELDNAME11": 11,
+ "FIELDName12": 12
})",
[](const Json::Value& value) {
return value.isMember("fieldName7") &&
- value.isMember("fieldName8") &&
+ value.isMember("FieldName8") &&
value.isMember("fieldName9") &&
- value.isMember("fieldName10") &&
- value.isMember("fIELDNAME11") &&
- value.isMember("fIELDName12");
+ value.isMember("FieldName10") &&
+ value.isMember("FIELDNAME11") &&
+ value.isMember("FIELDName12");
+ });
+ RunValidJsonTestWithValidator(
+ "FieldNameWithDoubleUnderscores", RECOMMENDED,
+ R"({
+ "fieldName13": 13,
+ "fieldName14": 14,
+ "fieldName15": 15,
+ "fieldName16": 16,
+ "fieldName17": 17,
+ "fieldName18": 18
+ })",
+ [](const Json::Value& value) {
+ return value.isMember("fieldName13") &&
+ value.isMember("fieldName14") &&
+ value.isMember("fieldName15") &&
+ value.isMember("fieldName16") &&
+ value.isMember("fieldName17") &&
+ value.isMember("fieldName18");
});
// Integer fields.
RunValidJsonTest(
- "Int32FieldMaxValue",
+ "Int32FieldMaxValue", REQUIRED,
R"({"optionalInt32": 2147483647})",
"optional_int32: 2147483647");
RunValidJsonTest(
- "Int32FieldMinValue",
+ "Int32FieldMinValue", REQUIRED,
R"({"optionalInt32": -2147483648})",
"optional_int32: -2147483648");
RunValidJsonTest(
- "Uint32FieldMaxValue",
+ "Uint32FieldMaxValue", REQUIRED,
R"({"optionalUint32": 4294967295})",
"optional_uint32: 4294967295");
RunValidJsonTest(
- "Int64FieldMaxValue",
+ "Int64FieldMaxValue", REQUIRED,
R"({"optionalInt64": "9223372036854775807"})",
"optional_int64: 9223372036854775807");
RunValidJsonTest(
- "Int64FieldMinValue",
+ "Int64FieldMinValue", REQUIRED,
R"({"optionalInt64": "-9223372036854775808"})",
"optional_int64: -9223372036854775808");
RunValidJsonTest(
- "Uint64FieldMaxValue",
+ "Uint64FieldMaxValue", REQUIRED,
R"({"optionalUint64": "18446744073709551615"})",
"optional_uint64: 18446744073709551615");
// While not the largest Int64, this is the largest
@@ -821,127 +969,127 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// work in some implementations, but should not be
// relied upon.
RunValidJsonTest(
- "Int64FieldMaxValueNotQuoted",
+ "Int64FieldMaxValueNotQuoted", REQUIRED,
R"({"optionalInt64": 9223372036854774784})",
"optional_int64: 9223372036854774784");
RunValidJsonTest(
- "Int64FieldMinValueNotQuoted",
+ "Int64FieldMinValueNotQuoted", REQUIRED,
R"({"optionalInt64": -9223372036854775808})",
"optional_int64: -9223372036854775808");
// Largest interoperable Uint64; see comment above
// for Int64FieldMaxValueNotQuoted.
RunValidJsonTest(
- "Uint64FieldMaxValueNotQuoted",
+ "Uint64FieldMaxValueNotQuoted", REQUIRED,
R"({"optionalUint64": 18446744073709549568})",
"optional_uint64: 18446744073709549568");
// Values can be represented as JSON strings.
RunValidJsonTest(
- "Int32FieldStringValue",
+ "Int32FieldStringValue", REQUIRED,
R"({"optionalInt32": "2147483647"})",
"optional_int32: 2147483647");
RunValidJsonTest(
- "Int32FieldStringValueEscaped",
+ "Int32FieldStringValueEscaped", REQUIRED,
R"({"optionalInt32": "2\u003147483647"})",
"optional_int32: 2147483647");
// Parsers reject out-of-bound integer values.
ExpectParseFailureForJson(
- "Int32FieldTooLarge",
+ "Int32FieldTooLarge", REQUIRED,
R"({"optionalInt32": 2147483648})");
ExpectParseFailureForJson(
- "Int32FieldTooSmall",
+ "Int32FieldTooSmall", REQUIRED,
R"({"optionalInt32": -2147483649})");
ExpectParseFailureForJson(
- "Uint32FieldTooLarge",
+ "Uint32FieldTooLarge", REQUIRED,
R"({"optionalUint32": 4294967296})");
ExpectParseFailureForJson(
- "Int64FieldTooLarge",
+ "Int64FieldTooLarge", REQUIRED,
R"({"optionalInt64": "9223372036854775808"})");
ExpectParseFailureForJson(
- "Int64FieldTooSmall",
+ "Int64FieldTooSmall", REQUIRED,
R"({"optionalInt64": "-9223372036854775809"})");
ExpectParseFailureForJson(
- "Uint64FieldTooLarge",
+ "Uint64FieldTooLarge", REQUIRED,
R"({"optionalUint64": "18446744073709551616"})");
// Parser reject non-integer numeric values as well.
ExpectParseFailureForJson(
- "Int32FieldNotInteger",
+ "Int32FieldNotInteger", REQUIRED,
R"({"optionalInt32": 0.5})");
ExpectParseFailureForJson(
- "Uint32FieldNotInteger",
+ "Uint32FieldNotInteger", REQUIRED,
R"({"optionalUint32": 0.5})");
ExpectParseFailureForJson(
- "Int64FieldNotInteger",
+ "Int64FieldNotInteger", REQUIRED,
R"({"optionalInt64": "0.5"})");
ExpectParseFailureForJson(
- "Uint64FieldNotInteger",
+ "Uint64FieldNotInteger", REQUIRED,
R"({"optionalUint64": "0.5"})");
// Integers but represented as float values are accepted.
RunValidJsonTest(
- "Int32FieldFloatTrailingZero",
+ "Int32FieldFloatTrailingZero", REQUIRED,
R"({"optionalInt32": 100000.000})",
"optional_int32: 100000");
RunValidJsonTest(
- "Int32FieldExponentialFormat",
+ "Int32FieldExponentialFormat", REQUIRED,
R"({"optionalInt32": 1e5})",
"optional_int32: 100000");
RunValidJsonTest(
- "Int32FieldMaxFloatValue",
+ "Int32FieldMaxFloatValue", REQUIRED,
R"({"optionalInt32": 2.147483647e9})",
"optional_int32: 2147483647");
RunValidJsonTest(
- "Int32FieldMinFloatValue",
+ "Int32FieldMinFloatValue", REQUIRED,
R"({"optionalInt32": -2.147483648e9})",
"optional_int32: -2147483648");
RunValidJsonTest(
- "Uint32FieldMaxFloatValue",
+ "Uint32FieldMaxFloatValue", REQUIRED,
R"({"optionalUint32": 4.294967295e9})",
"optional_uint32: 4294967295");
// Parser reject non-numeric values.
ExpectParseFailureForJson(
- "Int32FieldNotNumber",
+ "Int32FieldNotNumber", REQUIRED,
R"({"optionalInt32": "3x3"})");
ExpectParseFailureForJson(
- "Uint32FieldNotNumber",
+ "Uint32FieldNotNumber", REQUIRED,
R"({"optionalUint32": "3x3"})");
ExpectParseFailureForJson(
- "Int64FieldNotNumber",
+ "Int64FieldNotNumber", REQUIRED,
R"({"optionalInt64": "3x3"})");
ExpectParseFailureForJson(
- "Uint64FieldNotNumber",
+ "Uint64FieldNotNumber", REQUIRED,
R"({"optionalUint64": "3x3"})");
// JSON does not allow "+" on numric values.
ExpectParseFailureForJson(
- "Int32FieldPlusSign",
+ "Int32FieldPlusSign", REQUIRED,
R"({"optionalInt32": +1})");
// JSON doesn't allow leading 0s.
ExpectParseFailureForJson(
- "Int32FieldLeadingZero",
+ "Int32FieldLeadingZero", REQUIRED,
R"({"optionalInt32": 01})");
ExpectParseFailureForJson(
- "Int32FieldNegativeWithLeadingZero",
+ "Int32FieldNegativeWithLeadingZero", REQUIRED,
R"({"optionalInt32": -01})");
// String values must follow the same syntax rule. Specifically leading
// or traling spaces are not allowed.
ExpectParseFailureForJson(
- "Int32FieldLeadingSpace",
+ "Int32FieldLeadingSpace", REQUIRED,
R"({"optionalInt32": " 1"})");
ExpectParseFailureForJson(
- "Int32FieldTrailingSpace",
+ "Int32FieldTrailingSpace", REQUIRED,
R"({"optionalInt32": "1 "})");
// 64-bit values are serialized as strings.
RunValidJsonTestWithValidator(
- "Int64FieldBeString",
+ "Int64FieldBeString", RECOMMENDED,
R"({"optionalInt64": 1})",
[](const Json::Value& value) {
return value["optionalInt64"].type() == Json::stringValue &&
value["optionalInt64"].asString() == "1";
});
RunValidJsonTestWithValidator(
- "Uint64FieldBeString",
+ "Uint64FieldBeString", RECOMMENDED,
R"({"optionalUint64": 1})",
[](const Json::Value& value) {
return value["optionalUint64"].type() == Json::stringValue &&
@@ -950,73 +1098,73 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// Bool fields.
RunValidJsonTest(
- "BoolFieldTrue",
+ "BoolFieldTrue", REQUIRED,
R"({"optionalBool":true})",
"optional_bool: true");
RunValidJsonTest(
- "BoolFieldFalse",
+ "BoolFieldFalse", REQUIRED,
R"({"optionalBool":false})",
"optional_bool: false");
// Other forms are not allowed.
ExpectParseFailureForJson(
- "BoolFieldIntegerZero",
+ "BoolFieldIntegerZero", RECOMMENDED,
R"({"optionalBool":0})");
ExpectParseFailureForJson(
- "BoolFieldIntegerOne",
+ "BoolFieldIntegerOne", RECOMMENDED,
R"({"optionalBool":1})");
ExpectParseFailureForJson(
- "BoolFieldCamelCaseTrue",
+ "BoolFieldCamelCaseTrue", RECOMMENDED,
R"({"optionalBool":True})");
ExpectParseFailureForJson(
- "BoolFieldCamelCaseFalse",
+ "BoolFieldCamelCaseFalse", RECOMMENDED,
R"({"optionalBool":False})");
ExpectParseFailureForJson(
- "BoolFieldAllCapitalTrue",
+ "BoolFieldAllCapitalTrue", RECOMMENDED,
R"({"optionalBool":TRUE})");
ExpectParseFailureForJson(
- "BoolFieldAllCapitalFalse",
+ "BoolFieldAllCapitalFalse", RECOMMENDED,
R"({"optionalBool":FALSE})");
ExpectParseFailureForJson(
- "BoolFieldDoubleQuotedTrue",
+ "BoolFieldDoubleQuotedTrue", RECOMMENDED,
R"({"optionalBool":"true"})");
ExpectParseFailureForJson(
- "BoolFieldDoubleQuotedFalse",
+ "BoolFieldDoubleQuotedFalse", RECOMMENDED,
R"({"optionalBool":"false"})");
// Float fields.
RunValidJsonTest(
- "FloatFieldMinPositiveValue",
+ "FloatFieldMinPositiveValue", REQUIRED,
R"({"optionalFloat": 1.175494e-38})",
"optional_float: 1.175494e-38");
RunValidJsonTest(
- "FloatFieldMaxNegativeValue",
+ "FloatFieldMaxNegativeValue", REQUIRED,
R"({"optionalFloat": -1.175494e-38})",
"optional_float: -1.175494e-38");
RunValidJsonTest(
- "FloatFieldMaxPositiveValue",
+ "FloatFieldMaxPositiveValue", REQUIRED,
R"({"optionalFloat": 3.402823e+38})",
"optional_float: 3.402823e+38");
RunValidJsonTest(
- "FloatFieldMinNegativeValue",
+ "FloatFieldMinNegativeValue", REQUIRED,
R"({"optionalFloat": 3.402823e+38})",
"optional_float: 3.402823e+38");
// Values can be quoted.
RunValidJsonTest(
- "FloatFieldQuotedValue",
+ "FloatFieldQuotedValue", REQUIRED,
R"({"optionalFloat": "1"})",
"optional_float: 1");
// Special values.
RunValidJsonTest(
- "FloatFieldNan",
+ "FloatFieldNan", REQUIRED,
R"({"optionalFloat": "NaN"})",
"optional_float: nan");
RunValidJsonTest(
- "FloatFieldInfinity",
+ "FloatFieldInfinity", REQUIRED,
R"({"optionalFloat": "Infinity"})",
"optional_float: inf");
RunValidJsonTest(
- "FloatFieldNegativeInfinity",
+ "FloatFieldNegativeInfinity", REQUIRED,
R"({"optionalFloat": "-Infinity"})",
"optional_float: -inf");
// Non-cannonical Nan will be correctly normalized.
@@ -1027,68 +1175,68 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
message.set_optional_float(
WireFormatLite::DecodeFloat(0x7FA12345));
RunValidJsonTestWithProtobufInput(
- "FloatFieldNormalizeQuietNan", message,
+ "FloatFieldNormalizeQuietNan", REQUIRED, message,
"optional_float: nan");
// IEEE floating-point standard 64-bit signaling NaN:
// 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
message.set_optional_float(
WireFormatLite::DecodeFloat(0xFFB54321));
RunValidJsonTestWithProtobufInput(
- "FloatFieldNormalizeSignalingNan", message,
+ "FloatFieldNormalizeSignalingNan", REQUIRED, message,
"optional_float: nan");
}
// Special values must be quoted.
ExpectParseFailureForJson(
- "FloatFieldNanNotQuoted",
+ "FloatFieldNanNotQuoted", RECOMMENDED,
R"({"optionalFloat": NaN})");
ExpectParseFailureForJson(
- "FloatFieldInfinityNotQuoted",
+ "FloatFieldInfinityNotQuoted", RECOMMENDED,
R"({"optionalFloat": Infinity})");
ExpectParseFailureForJson(
- "FloatFieldNegativeInfinityNotQuoted",
+ "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
R"({"optionalFloat": -Infinity})");
// Parsers should reject out-of-bound values.
ExpectParseFailureForJson(
- "FloatFieldTooSmall",
+ "FloatFieldTooSmall", REQUIRED,
R"({"optionalFloat": -3.502823e+38})");
ExpectParseFailureForJson(
- "FloatFieldTooLarge",
+ "FloatFieldTooLarge", REQUIRED,
R"({"optionalFloat": 3.502823e+38})");
// Double fields.
RunValidJsonTest(
- "DoubleFieldMinPositiveValue",
+ "DoubleFieldMinPositiveValue", REQUIRED,
R"({"optionalDouble": 2.22507e-308})",
"optional_double: 2.22507e-308");
RunValidJsonTest(
- "DoubleFieldMaxNegativeValue",
+ "DoubleFieldMaxNegativeValue", REQUIRED,
R"({"optionalDouble": -2.22507e-308})",
"optional_double: -2.22507e-308");
RunValidJsonTest(
- "DoubleFieldMaxPositiveValue",
+ "DoubleFieldMaxPositiveValue", REQUIRED,
R"({"optionalDouble": 1.79769e+308})",
"optional_double: 1.79769e+308");
RunValidJsonTest(
- "DoubleFieldMinNegativeValue",
+ "DoubleFieldMinNegativeValue", REQUIRED,
R"({"optionalDouble": -1.79769e+308})",
"optional_double: -1.79769e+308");
// Values can be quoted.
RunValidJsonTest(
- "DoubleFieldQuotedValue",
+ "DoubleFieldQuotedValue", REQUIRED,
R"({"optionalDouble": "1"})",
"optional_double: 1");
// Speical values.
RunValidJsonTest(
- "DoubleFieldNan",
+ "DoubleFieldNan", REQUIRED,
R"({"optionalDouble": "NaN"})",
"optional_double: nan");
RunValidJsonTest(
- "DoubleFieldInfinity",
+ "DoubleFieldInfinity", REQUIRED,
R"({"optionalDouble": "Infinity"})",
"optional_double: inf");
RunValidJsonTest(
- "DoubleFieldNegativeInfinity",
+ "DoubleFieldNegativeInfinity", REQUIRED,
R"({"optionalDouble": "-Infinity"})",
"optional_double: -inf");
// Non-cannonical Nan will be correctly normalized.
@@ -1097,55 +1245,55 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
message.set_optional_double(
WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
RunValidJsonTestWithProtobufInput(
- "DoubleFieldNormalizeQuietNan", message,
+ "DoubleFieldNormalizeQuietNan", REQUIRED, message,
"optional_double: nan");
message.set_optional_double(
WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
RunValidJsonTestWithProtobufInput(
- "DoubleFieldNormalizeSignalingNan", message,
+ "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
"optional_double: nan");
}
// Special values must be quoted.
ExpectParseFailureForJson(
- "DoubleFieldNanNotQuoted",
+ "DoubleFieldNanNotQuoted", RECOMMENDED,
R"({"optionalDouble": NaN})");
ExpectParseFailureForJson(
- "DoubleFieldInfinityNotQuoted",
+ "DoubleFieldInfinityNotQuoted", RECOMMENDED,
R"({"optionalDouble": Infinity})");
ExpectParseFailureForJson(
- "DoubleFieldNegativeInfinityNotQuoted",
+ "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
R"({"optionalDouble": -Infinity})");
// Parsers should reject out-of-bound values.
ExpectParseFailureForJson(
- "DoubleFieldTooSmall",
+ "DoubleFieldTooSmall", REQUIRED,
R"({"optionalDouble": -1.89769e+308})");
ExpectParseFailureForJson(
- "DoubleFieldTooLarge",
+ "DoubleFieldTooLarge", REQUIRED,
R"({"optionalDouble": +1.89769e+308})");
// Enum fields.
RunValidJsonTest(
- "EnumField",
+ "EnumField", REQUIRED,
R"({"optionalNestedEnum": "FOO"})",
"optional_nested_enum: FOO");
// Enum values must be represented as strings.
ExpectParseFailureForJson(
- "EnumFieldNotQuoted",
+ "EnumFieldNotQuoted", REQUIRED,
R"({"optionalNestedEnum": FOO})");
// Numeric values are allowed.
RunValidJsonTest(
- "EnumFieldNumericValueZero",
+ "EnumFieldNumericValueZero", REQUIRED,
R"({"optionalNestedEnum": 0})",
"optional_nested_enum: FOO");
RunValidJsonTest(
- "EnumFieldNumericValueNonZero",
+ "EnumFieldNumericValueNonZero", REQUIRED,
R"({"optionalNestedEnum": 1})",
"optional_nested_enum: BAR");
// Unknown enum values are represented as numeric values.
RunValidJsonTestWithValidator(
- "EnumFieldUnknownValue",
+ "EnumFieldUnknownValue", REQUIRED,
R"({"optionalNestedEnum": 123})",
[](const Json::Value& value) {
return value["optionalNestedEnum"].type() == Json::intValue &&
@@ -1154,177 +1302,241 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// String fields.
RunValidJsonTest(
- "StringField",
+ "StringField", REQUIRED,
R"({"optionalString": "Hello world!"})",
"optional_string: \"Hello world!\"");
RunValidJsonTest(
- "StringFieldUnicode",
+ "StringFieldUnicode", REQUIRED,
// Google in Chinese.
R"({"optionalString": "谷歌"})",
R"(optional_string: "谷歌")");
RunValidJsonTest(
- "StringFieldEscape",
+ "StringFieldEscape", REQUIRED,
R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
R"(optional_string: "\"\\/\b\f\n\r\t")");
RunValidJsonTest(
- "StringFieldUnicodeEscape",
+ "StringFieldUnicodeEscape", REQUIRED,
R"({"optionalString": "\u8C37\u6B4C"})",
R"(optional_string: "谷歌")");
RunValidJsonTest(
- "StringFieldUnicodeEscapeWithLowercaseHexLetters",
+ "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
R"({"optionalString": "\u8c37\u6b4c"})",
R"(optional_string: "谷歌")");
RunValidJsonTest(
- "StringFieldSurrogatePair",
+ "StringFieldSurrogatePair", REQUIRED,
// The character is an emoji: grinning face with smiling eyes. 😁
R"({"optionalString": "\uD83D\uDE01"})",
R"(optional_string: "\xF0\x9F\x98\x81")");
// Unicode escapes must start with "\u" (lowercase u).
ExpectParseFailureForJson(
- "StringFieldUppercaseEscapeLetter",
+ "StringFieldUppercaseEscapeLetter", RECOMMENDED,
R"({"optionalString": "\U8C37\U6b4C"})");
ExpectParseFailureForJson(
- "StringFieldInvalidEscape",
+ "StringFieldInvalidEscape", RECOMMENDED,
R"({"optionalString": "\uXXXX\u6B4C"})");
ExpectParseFailureForJson(
- "StringFieldUnterminatedEscape",
+ "StringFieldUnterminatedEscape", RECOMMENDED,
R"({"optionalString": "\u8C3"})");
ExpectParseFailureForJson(
- "StringFieldUnpairedHighSurrogate",
+ "StringFieldUnpairedHighSurrogate", RECOMMENDED,
R"({"optionalString": "\uD800"})");
ExpectParseFailureForJson(
- "StringFieldUnpairedLowSurrogate",
+ "StringFieldUnpairedLowSurrogate", RECOMMENDED,
R"({"optionalString": "\uDC00"})");
ExpectParseFailureForJson(
- "StringFieldSurrogateInWrongOrder",
+ "StringFieldSurrogateInWrongOrder", RECOMMENDED,
R"({"optionalString": "\uDE01\uD83D"})");
ExpectParseFailureForJson(
- "StringFieldNotAString",
+ "StringFieldNotAString", REQUIRED,
R"({"optionalString": 12345})");
// Bytes fields.
RunValidJsonTest(
- "BytesField",
+ "BytesField", REQUIRED,
R"({"optionalBytes": "AQI="})",
R"(optional_bytes: "\x01\x02")");
ExpectParseFailureForJson(
- "BytesFieldNoPadding",
- R"({"optionalBytes": "AQI"})");
- ExpectParseFailureForJson(
- "BytesFieldInvalidBase64Characters",
+ "BytesFieldInvalidBase64Characters", REQUIRED,
R"({"optionalBytes": "-_=="})");
// Message fields.
RunValidJsonTest(
- "MessageField",
+ "MessageField", REQUIRED,
R"({"optionalNestedMessage": {"a": 1234}})",
"optional_nested_message: {a: 1234}");
// Oneof fields.
ExpectParseFailureForJson(
- "OneofFieldDuplicate",
+ "OneofFieldDuplicate", REQUIRED,
R"({"oneofUint32": 1, "oneofString": "test"})");
+ // Ensure zero values for oneof make it out/backs.
+ {
+ TestAllTypes message;
+ message.set_oneof_uint32(0);
+ RunValidProtobufTest(
+ "OneofZeroUint32", RECOMMENDED, message, "oneof_uint32: 0");
+ message.mutable_oneof_nested_message()->set_a(0);
+ RunValidProtobufTest(
+ "OneofZeroMessage", RECOMMENDED, message, "oneof_nested_message: {}");
+ message.set_oneof_string("");
+ RunValidProtobufTest(
+ "OneofZeroString", RECOMMENDED, message, "oneof_string: \"\"");
+ message.set_oneof_bytes("");
+ RunValidProtobufTest(
+ "OneofZeroBytes", RECOMMENDED, message, "oneof_bytes: \"\"");
+ message.set_oneof_bool(false);
+ RunValidProtobufTest(
+ "OneofZeroBool", RECOMMENDED, message, "oneof_bool: false");
+ message.set_oneof_uint64(0);
+ RunValidProtobufTest(
+ "OneofZeroUint64", RECOMMENDED, message, "oneof_uint64: 0");
+ message.set_oneof_float(0.0f);
+ RunValidProtobufTest(
+ "OneofZeroFloat", RECOMMENDED, message, "oneof_float: 0");
+ message.set_oneof_double(0.0);
+ RunValidProtobufTest(
+ "OneofZeroDouble", RECOMMENDED, message, "oneof_double: 0");
+ message.set_oneof_enum(TestAllTypes::FOO);
+ RunValidProtobufTest(
+ "OneofZeroEnum", RECOMMENDED, message, "oneof_enum: FOO");
+ }
+ RunValidJsonTest(
+ "OneofZeroUint32", RECOMMENDED,
+ R"({"oneofUint32": 0})", "oneof_uint32: 0");
+ RunValidJsonTest(
+ "OneofZeroMessage", RECOMMENDED,
+ R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
+ RunValidJsonTest(
+ "OneofZeroString", RECOMMENDED,
+ R"({"oneofString": ""})", "oneof_string: \"\"");
+ RunValidJsonTest(
+ "OneofZeroBytes", RECOMMENDED,
+ R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
+ RunValidJsonTest(
+ "OneofZeroBool", RECOMMENDED,
+ R"({"oneofBool": false})", "oneof_bool: false");
+ RunValidJsonTest(
+ "OneofZeroUint64", RECOMMENDED,
+ R"({"oneofUint64": 0})", "oneof_uint64: 0");
+ RunValidJsonTest(
+ "OneofZeroFloat", RECOMMENDED,
+ R"({"oneofFloat": 0.0})", "oneof_float: 0");
+ RunValidJsonTest(
+ "OneofZeroDouble", RECOMMENDED,
+ R"({"oneofDouble": 0.0})", "oneof_double: 0");
+ RunValidJsonTest(
+ "OneofZeroEnum", RECOMMENDED,
+ R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
// Repeated fields.
RunValidJsonTest(
- "PrimitiveRepeatedField",
+ "PrimitiveRepeatedField", REQUIRED,
R"({"repeatedInt32": [1, 2, 3, 4]})",
"repeated_int32: [1, 2, 3, 4]");
RunValidJsonTest(
- "EnumRepeatedField",
+ "EnumRepeatedField", REQUIRED,
R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
"repeated_nested_enum: [FOO, BAR, BAZ]");
RunValidJsonTest(
- "StringRepeatedField",
+ "StringRepeatedField", REQUIRED,
R"({"repeatedString": ["Hello", "world"]})",
R"(repeated_string: ["Hello", "world"])");
RunValidJsonTest(
- "BytesRepeatedField",
+ "BytesRepeatedField", REQUIRED,
R"({"repeatedBytes": ["AAEC", "AQI="]})",
R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
RunValidJsonTest(
- "MessageRepeatedField",
+ "MessageRepeatedField", REQUIRED,
R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
"repeated_nested_message: {a: 1234}"
"repeated_nested_message: {a: 5678}");
// Repeated field elements are of incorrect type.
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingIntegersGotBool",
+ "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
R"({"repeatedInt32": [1, false, 3, 4]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingIntegersGotString",
+ "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
R"({"repeatedInt32": [1, 2, "name", 4]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage",
+ "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingStringsGotInt",
+ "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
R"({"repeatedString": ["1", 2, "3", "4"]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingStringsGotBool",
+ "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
R"({"repeatedString": ["1", "2", false, "4"]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingStringsGotMessage",
+ "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingMessagesGotInt",
+ "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingMessagesGotBool",
+ "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
R"({"repeatedNestedMessage": [{"a": 1}, false]})");
ExpectParseFailureForJson(
- "RepeatedFieldWrongElementTypeExpectingMessagesGotString",
+ "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
// Trailing comma in the repeated field is not allowed.
ExpectParseFailureForJson(
- "RepeatedFieldTrailingComma",
+ "RepeatedFieldTrailingComma", RECOMMENDED,
R"({"repeatedInt32": [1, 2, 3, 4,]})");
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
+ "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
+ "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
+ ExpectParseFailureForJson(
+ "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
+ "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
// Map fields.
RunValidJsonTest(
- "Int32MapField",
+ "Int32MapField", REQUIRED,
R"({"mapInt32Int32": {"1": 2, "3": 4}})",
"map_int32_int32: {key: 1 value: 2}"
"map_int32_int32: {key: 3 value: 4}");
ExpectParseFailureForJson(
- "Int32MapFieldKeyNotQuoted",
+ "Int32MapFieldKeyNotQuoted", RECOMMENDED,
R"({"mapInt32Int32": {1: 2, 3: 4}})");
RunValidJsonTest(
- "Uint32MapField",
+ "Uint32MapField", REQUIRED,
R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
"map_uint32_uint32: {key: 1 value: 2}"
"map_uint32_uint32: {key: 3 value: 4}");
ExpectParseFailureForJson(
- "Uint32MapFieldKeyNotQuoted",
+ "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
R"({"mapUint32Uint32": {1: 2, 3: 4}})");
RunValidJsonTest(
- "Int64MapField",
+ "Int64MapField", REQUIRED,
R"({"mapInt64Int64": {"1": 2, "3": 4}})",
"map_int64_int64: {key: 1 value: 2}"
"map_int64_int64: {key: 3 value: 4}");
ExpectParseFailureForJson(
- "Int64MapFieldKeyNotQuoted",
+ "Int64MapFieldKeyNotQuoted", RECOMMENDED,
R"({"mapInt64Int64": {1: 2, 3: 4}})");
RunValidJsonTest(
- "Uint64MapField",
+ "Uint64MapField", REQUIRED,
R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
"map_uint64_uint64: {key: 1 value: 2}"
"map_uint64_uint64: {key: 3 value: 4}");
ExpectParseFailureForJson(
- "Uint64MapFieldKeyNotQuoted",
+ "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
R"({"mapUint64Uint64": {1: 2, 3: 4}})");
RunValidJsonTest(
- "BoolMapField",
+ "BoolMapField", REQUIRED,
R"({"mapBoolBool": {"true": true, "false": false}})",
"map_bool_bool: {key: true value: true}"
"map_bool_bool: {key: false value: false}");
ExpectParseFailureForJson(
- "BoolMapFieldKeyNotQuoted",
+ "BoolMapFieldKeyNotQuoted", RECOMMENDED,
R"({"mapBoolBool": {true: true, false: false}})");
RunValidJsonTest(
- "MessageMapField",
+ "MessageMapField", REQUIRED,
R"({
"mapStringNestedMessage": {
"hello": {"a": 1234},
@@ -1343,21 +1555,21 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
)");
// Since Map keys are represented as JSON strings, escaping should be allowed.
RunValidJsonTest(
- "Int32MapEscapedKey",
+ "Int32MapEscapedKey", REQUIRED,
R"({"mapInt32Int32": {"\u0031": 2}})",
"map_int32_int32: {key: 1 value: 2}");
RunValidJsonTest(
- "Int64MapEscapedKey",
+ "Int64MapEscapedKey", REQUIRED,
R"({"mapInt64Int64": {"\u0031": 2}})",
"map_int64_int64: {key: 1 value: 2}");
RunValidJsonTest(
- "BoolMapEscapedKey",
+ "BoolMapEscapedKey", REQUIRED,
R"({"mapBoolBool": {"tr\u0075e": true}})",
"map_bool_bool: {key: true value: true}");
// "null" is accepted for all fields types.
RunValidJsonTest(
- "AllFieldAcceptNull",
+ "AllFieldAcceptNull", REQUIRED,
R"({
"optionalInt32": null,
"optionalInt64": null,
@@ -1385,59 +1597,71 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// Repeated field elements cannot be null.
ExpectParseFailureForJson(
- "RepeatedFieldPrimitiveElementIsNull",
+ "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
R"({"repeatedInt32": [1, null, 2]})");
ExpectParseFailureForJson(
- "RepeatedFieldMessageElementIsNull",
+ "RepeatedFieldMessageElementIsNull", RECOMMENDED,
R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
// Map field keys cannot be null.
ExpectParseFailureForJson(
- "MapFieldKeyIsNull",
+ "MapFieldKeyIsNull", RECOMMENDED,
R"({"mapInt32Int32": {null: 1}})");
// Map field values cannot be null.
ExpectParseFailureForJson(
- "MapFieldValueIsNull",
+ "MapFieldValueIsNull", RECOMMENDED,
R"({"mapInt32Int32": {"0": null}})");
+ // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
+ // quotes.
+ ExpectParseFailureForJson(
+ "StringFieldSingleQuoteKey", RECOMMENDED,
+ R"({'optionalString': "Hello world!"})");
+ ExpectParseFailureForJson(
+ "StringFieldSingleQuoteValue", RECOMMENDED,
+ R"({"optionalString": 'Hello world!'})");
+ ExpectParseFailureForJson(
+ "StringFieldSingleQuoteBoth", RECOMMENDED,
+ R"({'optionalString': 'Hello world!'})");
+
// Wrapper types.
RunValidJsonTest(
- "OptionalBoolWrapper",
+ "OptionalBoolWrapper", REQUIRED,
R"({"optionalBoolWrapper": false})",
"optional_bool_wrapper: {value: false}");
RunValidJsonTest(
- "OptionalInt32Wrapper",
+ "OptionalInt32Wrapper", REQUIRED,
R"({"optionalInt32Wrapper": 0})",
"optional_int32_wrapper: {value: 0}");
RunValidJsonTest(
- "OptionalUint32Wrapper",
+ "OptionalUint32Wrapper", REQUIRED,
R"({"optionalUint32Wrapper": 0})",
"optional_uint32_wrapper: {value: 0}");
RunValidJsonTest(
- "OptionalInt64Wrapper",
+ "OptionalInt64Wrapper", REQUIRED,
R"({"optionalInt64Wrapper": 0})",
"optional_int64_wrapper: {value: 0}");
RunValidJsonTest(
- "OptionalUint64Wrapper",
+ "OptionalUint64Wrapper", REQUIRED,
R"({"optionalUint64Wrapper": 0})",
"optional_uint64_wrapper: {value: 0}");
RunValidJsonTest(
- "OptionalFloatWrapper",
+ "OptionalFloatWrapper", REQUIRED,
R"({"optionalFloatWrapper": 0})",
"optional_float_wrapper: {value: 0}");
RunValidJsonTest(
- "OptionalDoubleWrapper",
+ "OptionalDoubleWrapper", REQUIRED,
R"({"optionalDoubleWrapper": 0})",
"optional_double_wrapper: {value: 0}");
RunValidJsonTest(
- "OptionalStringWrapper",
+ "OptionalStringWrapper", REQUIRED,
R"({"optionalStringWrapper": ""})",
R"(optional_string_wrapper: {value: ""})");
RunValidJsonTest(
- "OptionalBytesWrapper",
+ "OptionalBytesWrapper", REQUIRED,
R"({"optionalBytesWrapper": ""})",
R"(optional_bytes_wrapper: {value: ""})");
RunValidJsonTest(
- "OptionalWrapperTypesWithNonDefaultValue",
+ "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
R"({
"optionalBoolWrapper": true,
"optionalInt32Wrapper": 1,
@@ -1461,56 +1685,56 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
optional_bytes_wrapper: {value: "\x01\x02"}
)");
RunValidJsonTest(
- "RepeatedBoolWrapper",
+ "RepeatedBoolWrapper", REQUIRED,
R"({"repeatedBoolWrapper": [true, false]})",
"repeated_bool_wrapper: {value: true}"
"repeated_bool_wrapper: {value: false}");
RunValidJsonTest(
- "RepeatedInt32Wrapper",
+ "RepeatedInt32Wrapper", REQUIRED,
R"({"repeatedInt32Wrapper": [0, 1]})",
"repeated_int32_wrapper: {value: 0}"
"repeated_int32_wrapper: {value: 1}");
RunValidJsonTest(
- "RepeatedUint32Wrapper",
+ "RepeatedUint32Wrapper", REQUIRED,
R"({"repeatedUint32Wrapper": [0, 1]})",
"repeated_uint32_wrapper: {value: 0}"
"repeated_uint32_wrapper: {value: 1}");
RunValidJsonTest(
- "RepeatedInt64Wrapper",
+ "RepeatedInt64Wrapper", REQUIRED,
R"({"repeatedInt64Wrapper": [0, 1]})",
"repeated_int64_wrapper: {value: 0}"
"repeated_int64_wrapper: {value: 1}");
RunValidJsonTest(
- "RepeatedUint64Wrapper",
+ "RepeatedUint64Wrapper", REQUIRED,
R"({"repeatedUint64Wrapper": [0, 1]})",
"repeated_uint64_wrapper: {value: 0}"
"repeated_uint64_wrapper: {value: 1}");
RunValidJsonTest(
- "RepeatedFloatWrapper",
+ "RepeatedFloatWrapper", REQUIRED,
R"({"repeatedFloatWrapper": [0, 1]})",
"repeated_float_wrapper: {value: 0}"
"repeated_float_wrapper: {value: 1}");
RunValidJsonTest(
- "RepeatedDoubleWrapper",
+ "RepeatedDoubleWrapper", REQUIRED,
R"({"repeatedDoubleWrapper": [0, 1]})",
"repeated_double_wrapper: {value: 0}"
"repeated_double_wrapper: {value: 1}");
RunValidJsonTest(
- "RepeatedStringWrapper",
+ "RepeatedStringWrapper", REQUIRED,
R"({"repeatedStringWrapper": ["", "AQI="]})",
R"(
repeated_string_wrapper: {value: ""}
repeated_string_wrapper: {value: "AQI="}
)");
RunValidJsonTest(
- "RepeatedBytesWrapper",
+ "RepeatedBytesWrapper", REQUIRED,
R"({"repeatedBytesWrapper": ["", "AQI="]})",
R"(
repeated_bytes_wrapper: {value: ""}
repeated_bytes_wrapper: {value: "\x01\x02"}
)");
RunValidJsonTest(
- "WrapperTypesWithNullValue",
+ "WrapperTypesWithNullValue", REQUIRED,
R"({
"optionalBoolWrapper": null,
"optionalInt32Wrapper": null,
@@ -1535,55 +1759,55 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// Duration
RunValidJsonTest(
- "DurationMinValue",
+ "DurationMinValue", REQUIRED,
R"({"optionalDuration": "-315576000000.999999999s"})",
"optional_duration: {seconds: -315576000000 nanos: -999999999}");
RunValidJsonTest(
- "DurationMaxValue",
+ "DurationMaxValue", REQUIRED,
R"({"optionalDuration": "315576000000.999999999s"})",
"optional_duration: {seconds: 315576000000 nanos: 999999999}");
RunValidJsonTest(
- "DurationRepeatedValue",
+ "DurationRepeatedValue", REQUIRED,
R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
"repeated_duration: {seconds: 1 nanos: 500000000}"
"repeated_duration: {seconds: -1 nanos: -500000000}");
ExpectParseFailureForJson(
- "DurationMissingS",
+ "DurationMissingS", REQUIRED,
R"({"optionalDuration": "1"})");
ExpectParseFailureForJson(
- "DurationJsonInputTooSmall",
+ "DurationJsonInputTooSmall", REQUIRED,
R"({"optionalDuration": "-315576000001.000000000s"})");
ExpectParseFailureForJson(
- "DurationJsonInputTooLarge",
+ "DurationJsonInputTooLarge", REQUIRED,
R"({"optionalDuration": "315576000001.000000000s"})");
ExpectSerializeFailureForJson(
- "DurationProtoInputTooSmall",
+ "DurationProtoInputTooSmall", REQUIRED,
"optional_duration: {seconds: -315576000001 nanos: 0}");
ExpectSerializeFailureForJson(
- "DurationProtoInputTooLarge",
+ "DurationProtoInputTooLarge", REQUIRED,
"optional_duration: {seconds: 315576000001 nanos: 0}");
RunValidJsonTestWithValidator(
- "DurationHasZeroFractionalDigit",
+ "DurationHasZeroFractionalDigit", RECOMMENDED,
R"({"optionalDuration": "1.000000000s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1s";
});
RunValidJsonTestWithValidator(
- "DurationHas3FractionalDigits",
+ "DurationHas3FractionalDigits", RECOMMENDED,
R"({"optionalDuration": "1.010000000s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1.010s";
});
RunValidJsonTestWithValidator(
- "DurationHas6FractionalDigits",
+ "DurationHas6FractionalDigits", RECOMMENDED,
R"({"optionalDuration": "1.000010000s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1.000010s";
});
RunValidJsonTestWithValidator(
- "DurationHas9FractionalDigits",
+ "DurationHas9FractionalDigits", RECOMMENDED,
R"({"optionalDuration": "1.000000010s"})",
[](const Json::Value& value) {
return value["optionalDuration"].asString() == "1.000000010s";
@@ -1591,15 +1815,15 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// Timestamp
RunValidJsonTest(
- "TimestampMinValue",
+ "TimestampMinValue", REQUIRED,
R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
"optional_timestamp: {seconds: -62135596800}");
RunValidJsonTest(
- "TimestampMaxValue",
+ "TimestampMaxValue", REQUIRED,
R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
"optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
RunValidJsonTest(
- "TimestampRepeatedValue",
+ "TimestampRepeatedValue", REQUIRED,
R"({
"repeatedTimestamp": [
"0001-01-01T00:00:00Z",
@@ -1609,68 +1833,68 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
"repeated_timestamp: {seconds: -62135596800}"
"repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
RunValidJsonTest(
- "TimestampWithPositiveOffset",
+ "TimestampWithPositiveOffset", REQUIRED,
R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
"optional_timestamp: {seconds: 0}");
RunValidJsonTest(
- "TimestampWithNegativeOffset",
+ "TimestampWithNegativeOffset", REQUIRED,
R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
"optional_timestamp: {seconds: 0}");
ExpectParseFailureForJson(
- "TimestampJsonInputTooSmall",
+ "TimestampJsonInputTooSmall", REQUIRED,
R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
ExpectParseFailureForJson(
- "TimestampJsonInputTooLarge",
+ "TimestampJsonInputTooLarge", REQUIRED,
R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
ExpectParseFailureForJson(
- "TimestampJsonInputMissingZ",
+ "TimestampJsonInputMissingZ", REQUIRED,
R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
ExpectParseFailureForJson(
- "TimestampJsonInputMissingT",
+ "TimestampJsonInputMissingT", REQUIRED,
R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
ExpectParseFailureForJson(
- "TimestampJsonInputLowercaseZ",
+ "TimestampJsonInputLowercaseZ", REQUIRED,
R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
ExpectParseFailureForJson(
- "TimestampJsonInputLowercaseT",
+ "TimestampJsonInputLowercaseT", REQUIRED,
R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
ExpectSerializeFailureForJson(
- "TimestampProtoInputTooSmall",
+ "TimestampProtoInputTooSmall", REQUIRED,
"optional_timestamp: {seconds: -62135596801}");
ExpectSerializeFailureForJson(
- "TimestampProtoInputTooLarge",
+ "TimestampProtoInputTooLarge", REQUIRED,
"optional_timestamp: {seconds: 253402300800}");
RunValidJsonTestWithValidator(
- "TimestampZeroNormalized",
+ "TimestampZeroNormalized", RECOMMENDED,
R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00Z";
});
RunValidJsonTestWithValidator(
- "TimestampHasZeroFractionalDigit",
+ "TimestampHasZeroFractionalDigit", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00Z";
});
RunValidJsonTestWithValidator(
- "TimestampHas3FractionalDigits",
+ "TimestampHas3FractionalDigits", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00.010Z";
});
RunValidJsonTestWithValidator(
- "TimestampHas6FractionalDigits",
+ "TimestampHas6FractionalDigits", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
"1970-01-01T00:00:00.000010Z";
});
RunValidJsonTestWithValidator(
- "TimestampHas9FractionalDigits",
+ "TimestampHas9FractionalDigits", RECOMMENDED,
R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
[](const Json::Value& value) {
return value["optionalTimestamp"].asString() ==
@@ -1679,25 +1903,25 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// FieldMask
RunValidJsonTest(
- "FieldMask",
+ "FieldMask", REQUIRED,
R"({"optionalFieldMask": "foo,barBaz"})",
R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
ExpectParseFailureForJson(
- "FieldMaskInvalidCharacter",
+ "FieldMaskInvalidCharacter", RECOMMENDED,
R"({"optionalFieldMask": "foo,bar_bar"})");
ExpectSerializeFailureForJson(
- "FieldMaskPathsDontRoundTrip",
+ "FieldMaskPathsDontRoundTrip", RECOMMENDED,
R"(optional_field_mask: {paths: "fooBar"})");
ExpectSerializeFailureForJson(
- "FieldMaskNumbersDontRoundTrip",
+ "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
R"(optional_field_mask: {paths: "foo_3_bar"})");
ExpectSerializeFailureForJson(
- "FieldMaskTooManyUnderscore",
+ "FieldMaskTooManyUnderscore", RECOMMENDED,
R"(optional_field_mask: {paths: "foo__bar"})");
// Struct
RunValidJsonTest(
- "Struct",
+ "Struct", REQUIRED,
R"({
"optionalStruct": {
"nullValue": null,
@@ -1763,27 +1987,27 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
)");
// Value
RunValidJsonTest(
- "ValueAcceptInteger",
+ "ValueAcceptInteger", REQUIRED,
R"({"optionalValue": 1})",
"optional_value: { number_value: 1}");
RunValidJsonTest(
- "ValueAcceptFloat",
+ "ValueAcceptFloat", REQUIRED,
R"({"optionalValue": 1.5})",
"optional_value: { number_value: 1.5}");
RunValidJsonTest(
- "ValueAcceptBool",
+ "ValueAcceptBool", REQUIRED,
R"({"optionalValue": false})",
"optional_value: { bool_value: false}");
RunValidJsonTest(
- "ValueAcceptNull",
+ "ValueAcceptNull", REQUIRED,
R"({"optionalValue": null})",
"optional_value: { null_value: NULL_VALUE}");
RunValidJsonTest(
- "ValueAcceptString",
+ "ValueAcceptString", REQUIRED,
R"({"optionalValue": "hello"})",
R"(optional_value: { string_value: "hello"})");
RunValidJsonTest(
- "ValueAcceptList",
+ "ValueAcceptList", REQUIRED,
R"({"optionalValue": [0, "hello"]})",
R"(
optional_value: {
@@ -1798,7 +2022,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "ValueAcceptObject",
+ "ValueAcceptObject", REQUIRED,
R"({"optionalValue": {"value": 1}})",
R"(
optional_value: {
@@ -1815,7 +2039,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
// Any
RunValidJsonTest(
- "Any",
+ "Any", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/conformance.TestAllTypes",
@@ -1830,7 +2054,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyNested",
+ "AnyNested", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Any",
@@ -1851,7 +2075,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
)");
// The special "@type" tag is not required to appear first.
RunValidJsonTest(
- "AnyUnorderedTypeTag",
+ "AnyUnorderedTypeTag", REQUIRED,
R"({
"optionalAny": {
"optionalInt32": 12345,
@@ -1867,7 +2091,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
)");
// Well-known types in Any.
RunValidJsonTest(
- "AnyWithInt32ValueWrapper",
+ "AnyWithInt32ValueWrapper", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Int32Value",
@@ -1882,7 +2106,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyWithDuration",
+ "AnyWithDuration", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Duration",
@@ -1898,7 +2122,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyWithTimestamp",
+ "AnyWithTimestamp", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Timestamp",
@@ -1914,7 +2138,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyWithFieldMask",
+ "AnyWithFieldMask", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.FieldMask",
@@ -1929,7 +2153,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyWithStruct",
+ "AnyWithStruct", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Struct",
@@ -1951,7 +2175,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyWithValueForJsonObject",
+ "AnyWithValueForJsonObject", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Value",
@@ -1975,7 +2199,7 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
}
)");
RunValidJsonTest(
- "AnyWithValueForInteger",
+ "AnyWithValueForInteger", REQUIRED,
R"({
"optionalAny": {
"@type": "type.googleapis.com/google.protobuf.Value",
diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h
index c9c5213c..08f16b8f 100644
--- a/conformance/conformance_test.h
+++ b/conformance/conformance_test.h
@@ -91,7 +91,7 @@ class ConformanceTestRunner {
//
class ConformanceTestSuite {
public:
- ConformanceTestSuite() : verbose_(false) {}
+ ConformanceTestSuite() : verbose_(false), enforce_recommended_(false) {}
void SetVerbose(bool verbose) { verbose_ = verbose; }
@@ -104,6 +104,18 @@ class ConformanceTestSuite {
void SetFailureList(const std::string& filename,
const std::vector<std::string>& failure_list);
+ // Whether to require the testee to pass RECOMMENDED tests. By default failing
+ // a RECOMMENDED test case will not fail the entire suite but will only
+ // generated a warning. If this flag is set to true, RECOMMENDED tests will
+ // be treated the same way as REQUIRED tests and failing a RECOMMENDED test
+ // case will cause the entire test suite to fail as well. An implementation
+ // can enable this if it wants to be strictly conforming to protobuf spec.
+ // See the comments about ConformanceLevel below to learn more about the
+ // difference between REQUIRED and RECOMMENDED test cases.
+ void SetEnforceRecommended(bool value) {
+ enforce_recommended_ = value;
+ }
+
// Run all the conformance tests against the given test runner.
// Test output will be stored in "output".
//
@@ -113,8 +125,27 @@ class ConformanceTestSuite {
bool RunSuite(ConformanceTestRunner* runner, std::string* output);
private:
+ // Test cases are classified into a few categories:
+ // REQUIRED: the test case must be passed for an implementation to be
+ // interoperable with other implementations. For example, a
+ // parser implementaiton must accept both packed and unpacked
+ // form of repeated primitive fields.
+ // RECOMMENDED: the test case is not required for the implementation to
+ // be interoperable with other implementations, but is
+ // recommended for best performance and compatibility. For
+ // example, a proto3 serializer should serialize repeated
+ // primitive fields in packed form, but an implementation
+ // failing to do so will still be able to communicate with
+ // other implementations.
+ enum ConformanceLevel {
+ REQUIRED = 0,
+ RECOMMENDED = 1,
+ };
+ string ConformanceLevelToString(ConformanceLevel level);
+
void ReportSuccess(const std::string& test_name);
void ReportFailure(const string& test_name,
+ ConformanceLevel level,
const conformance::ConformanceRequest& request,
const conformance::ConformanceResponse& response,
const char* fmt, ...);
@@ -124,28 +155,42 @@ class ConformanceTestSuite {
void RunTest(const std::string& test_name,
const conformance::ConformanceRequest& request,
conformance::ConformanceResponse* response);
- void RunValidInputTest(const string& test_name, const string& input,
+ void RunValidInputTest(const string& test_name,
+ ConformanceLevel level,
+ const string& input,
conformance::WireFormat input_format,
const string& equivalent_text_format,
conformance::WireFormat requested_output);
- void RunValidJsonTest(const string& test_name, const string& input_json,
+ void RunValidJsonTest(const string& test_name,
+ ConformanceLevel level,
+ const string& input_json,
const string& equivalent_text_format);
void RunValidJsonTestWithProtobufInput(const string& test_name,
+ ConformanceLevel level,
const conformance::TestAllTypes& input,
const string& equivalent_text_format);
+ void RunValidProtobufTest(const string& test_name,
+ ConformanceLevel level,
+ const conformance::TestAllTypes& input,
+ const string& equivalent_text_format);
typedef std::function<bool(const Json::Value&)> Validator;
void RunValidJsonTestWithValidator(const string& test_name,
+ ConformanceLevel level,
const string& input_json,
const Validator& validator);
void ExpectParseFailureForJson(const string& test_name,
+ ConformanceLevel level,
const string& input_json);
void ExpectSerializeFailureForJson(const string& test_name,
+ ConformanceLevel level,
const string& text_format);
void ExpectParseFailureForProto(const std::string& proto,
- const std::string& test_name);
+ const std::string& test_name,
+ ConformanceLevel level);
void ExpectHardParseFailureForProto(const std::string& proto,
- const std::string& test_name);
+ const std::string& test_name,
+ ConformanceLevel level);
void TestPrematureEOFForType(google::protobuf::FieldDescriptor::Type type);
bool CheckSetEmpty(const set<string>& set_to_check,
const std::string& write_to_file, const std::string& msg);
@@ -153,6 +198,7 @@ class ConformanceTestSuite {
int successes_;
int expected_failures_;
bool verbose_;
+ bool enforce_recommended_;
std::string output_;
std::string failure_list_filename_;
diff --git a/conformance/conformance_test_runner.cc b/conformance/conformance_test_runner.cc
index d6b1175c..7e91d388 100644
--- a/conformance/conformance_test_runner.cc
+++ b/conformance/conformance_test_runner.cc
@@ -251,6 +251,16 @@ void UsageError() {
" should contain one test name per\n");
fprintf(stderr,
" line. Use '#' for comments.\n");
+ fprintf(stderr,
+ " --enforce_recommended Enforce that recommended test\n");
+ fprintf(stderr,
+ " cases are also passing. Specify\n");
+ fprintf(stderr,
+ " this flag if you want to be\n");
+ fprintf(stderr,
+ " strictly conforming to protobuf\n");
+ fprintf(stderr,
+ " spec.\n");
exit(1);
}
@@ -290,6 +300,8 @@ int main(int argc, char *argv[]) {
ParseFailureList(argv[arg], &failure_list);
} else if (strcmp(argv[arg], "--verbose") == 0) {
suite.SetVerbose(true);
+ } else if (strcmp(argv[arg], "--enforce_recommended") == 0) {
+ suite.SetEnforceRecommended(true);
} else if (argv[arg][0] == '-') {
fprintf(stderr, "Unknown option: %s\n", argv[arg]);
UsageError();
diff --git a/conformance/failure_list_cpp.txt b/conformance/failure_list_cpp.txt
index 839e5210..508be506 100644
--- a/conformance/failure_list_cpp.txt
+++ b/conformance/failure_list_cpp.txt
@@ -7,42 +7,47 @@
# TODO(haberman): insert links to corresponding bugs tracking the issue.
# Should we use GitHub issues or the Google-internal bug tracker?
-FieldMaskNumbersDontRoundTrip.JsonOutput
-FieldMaskPathsDontRoundTrip.JsonOutput
-FieldMaskTooManyUnderscore.JsonOutput
-JsonInput.AnyUnorderedTypeTag.JsonOutput
-JsonInput.AnyUnorderedTypeTag.ProtobufOutput
-JsonInput.BoolFieldDoubleQuotedFalse
-JsonInput.BoolFieldDoubleQuotedTrue
-JsonInput.BytesFieldNoPadding
-JsonInput.DoubleFieldTooSmall
-JsonInput.DurationHasZeroFractionalDigit.Validator
-JsonInput.EnumFieldUnknownValue.Validator
-JsonInput.FieldMaskInvalidCharacter
-JsonInput.FieldNameDuplicate
-JsonInput.FieldNameDuplicateDifferentCasing1
-JsonInput.FieldNameDuplicateDifferentCasing2
-JsonInput.FieldNameInLowerCamelCase.Validator
-JsonInput.FieldNameInSnakeCase.JsonOutput
-JsonInput.FieldNameInSnakeCase.ProtobufOutput
-JsonInput.FieldNameNotQuoted
-JsonInput.MapFieldValueIsNull
-JsonInput.RepeatedFieldMessageElementIsNull
-JsonInput.RepeatedFieldPrimitiveElementIsNull
-JsonInput.RepeatedFieldTrailingComma
-JsonInput.StringFieldUppercaseEscapeLetter
-JsonInput.TrailingCommaInAnObject
-JsonInput.WrapperTypesWithNullValue.JsonOutput
-JsonInput.WrapperTypesWithNullValue.ProtobufOutput
-ProtobufInput.PrematureEofBeforeKnownRepeatedValue.MESSAGE
-ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
-ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
-ProtobufInput.PrematureEofInPackedField.BOOL
-ProtobufInput.PrematureEofInPackedField.ENUM
-ProtobufInput.PrematureEofInPackedField.INT32
-ProtobufInput.PrematureEofInPackedField.INT64
-ProtobufInput.PrematureEofInPackedField.SINT32
-ProtobufInput.PrematureEofInPackedField.SINT64
-ProtobufInput.PrematureEofInPackedField.UINT32
-ProtobufInput.PrematureEofInPackedField.UINT64
-ProtobufInput.PrematureEofInsideKnownRepeatedValue.MESSAGE
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.JsonInput.BoolFieldDoubleQuotedFalse
+Recommended.JsonInput.BoolFieldDoubleQuotedTrue
+Recommended.JsonInput.FieldMaskInvalidCharacter
+Recommended.JsonInput.FieldNameDuplicate
+Recommended.JsonInput.FieldNameDuplicateDifferentCasing1
+Recommended.JsonInput.FieldNameDuplicateDifferentCasing2
+Recommended.JsonInput.FieldNameNotQuoted
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.JsonOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.ProtobufOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.Validator
+Recommended.JsonInput.MapFieldValueIsNull
+Recommended.JsonInput.RepeatedFieldMessageElementIsNull
+Recommended.JsonInput.RepeatedFieldPrimitiveElementIsNull
+Recommended.JsonInput.RepeatedFieldTrailingComma
+Recommended.JsonInput.RepeatedFieldTrailingCommaWithNewlines
+Recommended.JsonInput.RepeatedFieldTrailingCommaWithSpace
+Recommended.JsonInput.RepeatedFieldTrailingCommaWithSpaceCommaSpace
+Recommended.JsonInput.StringFieldSingleQuoteBoth
+Recommended.JsonInput.StringFieldSingleQuoteKey
+Recommended.JsonInput.StringFieldSingleQuoteValue
+Recommended.JsonInput.StringFieldUppercaseEscapeLetter
+Recommended.JsonInput.TrailingCommaInAnObject
+Recommended.JsonInput.TrailingCommaInAnObjectWithNewlines
+Recommended.JsonInput.TrailingCommaInAnObjectWithSpace
+Recommended.JsonInput.TrailingCommaInAnObjectWithSpaceCommaSpace
+Required.JsonInput.DoubleFieldTooSmall
+Required.JsonInput.FieldNameInLowerCamelCase.Validator
+Required.JsonInput.FieldNameInSnakeCase.JsonOutput
+Required.JsonInput.FieldNameInSnakeCase.ProtobufOutput
+Required.ProtobufInput.PrematureEofBeforeKnownRepeatedValue.MESSAGE
+Required.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.ProtobufInput.PrematureEofInPackedField.BOOL
+Required.ProtobufInput.PrematureEofInPackedField.ENUM
+Required.ProtobufInput.PrematureEofInPackedField.INT32
+Required.ProtobufInput.PrematureEofInPackedField.INT64
+Required.ProtobufInput.PrematureEofInPackedField.SINT32
+Required.ProtobufInput.PrematureEofInPackedField.SINT64
+Required.ProtobufInput.PrematureEofInPackedField.UINT32
+Required.ProtobufInput.PrematureEofInPackedField.UINT64
+Required.ProtobufInput.PrematureEofInsideKnownRepeatedValue.MESSAGE
diff --git a/conformance/failure_list_csharp.txt b/conformance/failure_list_csharp.txt
index 1716bcbd..84f46fab 100644
--- a/conformance/failure_list_csharp.txt
+++ b/conformance/failure_list_csharp.txt
@@ -1,7 +1,2 @@
-JsonInput.FieldNameInLowerCamelCase.Validator
-JsonInput.FieldNameInSnakeCase.JsonOutput
-JsonInput.FieldNameInSnakeCase.ProtobufOutput
-JsonInput.FieldNameWithMixedCases.JsonOutput
-JsonInput.FieldNameWithMixedCases.ProtobufOutput
-JsonInput.FieldNameWithMixedCases.Validator
-JsonInput.OriginalProtoFieldName.JsonOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.JsonOutput
+Required.JsonInput.FieldNameInSnakeCase.JsonOutput
diff --git a/conformance/failure_list_java.txt b/conformance/failure_list_java.txt
index 850712bd..c9007d68 100644
--- a/conformance/failure_list_java.txt
+++ b/conformance/failure_list_java.txt
@@ -4,40 +4,46 @@
# By listing them here we can keep tabs on which ones are failing and be sure
# that we don't introduce regressions in other tests.
-FieldMaskNumbersDontRoundTrip.JsonOutput
-FieldMaskPathsDontRoundTrip.JsonOutput
-FieldMaskTooManyUnderscore.JsonOutput
-JsonInput.BoolFieldAllCapitalFalse
-JsonInput.BoolFieldAllCapitalTrue
-JsonInput.BoolFieldCamelCaseFalse
-JsonInput.BoolFieldCamelCaseTrue
-JsonInput.BoolFieldDoubleQuotedFalse
-JsonInput.BoolFieldDoubleQuotedTrue
-JsonInput.BoolMapFieldKeyNotQuoted
-JsonInput.DoubleFieldInfinityNotQuoted
-JsonInput.DoubleFieldNanNotQuoted
-JsonInput.DoubleFieldNegativeInfinityNotQuoted
-JsonInput.EnumFieldNotQuoted
-JsonInput.FieldMaskInvalidCharacter
-JsonInput.FieldNameDuplicate
-JsonInput.FieldNameInSnakeCase.JsonOutput
-JsonInput.FieldNameNotQuoted
-JsonInput.FloatFieldInfinityNotQuoted
-JsonInput.FloatFieldNanNotQuoted
-JsonInput.FloatFieldNegativeInfinityNotQuoted
-JsonInput.Int32FieldLeadingZero
-JsonInput.Int32FieldNegativeWithLeadingZero
-JsonInput.Int32FieldPlusSign
-JsonInput.Int32MapFieldKeyNotQuoted
-JsonInput.Int64MapFieldKeyNotQuoted
-JsonInput.JsonWithComments
-JsonInput.OriginalProtoFieldName.JsonOutput
-JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotBool
-JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
-JsonInput.StringFieldNotAString
-JsonInput.StringFieldSurrogateInWrongOrder
-JsonInput.StringFieldUnpairedHighSurrogate
-JsonInput.StringFieldUnpairedLowSurrogate
-JsonInput.StringFieldUppercaseEscapeLetter
-JsonInput.Uint32MapFieldKeyNotQuoted
-JsonInput.Uint64MapFieldKeyNotQuoted
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.JsonInput.BoolFieldAllCapitalFalse
+Recommended.JsonInput.BoolFieldAllCapitalTrue
+Recommended.JsonInput.BoolFieldCamelCaseFalse
+Recommended.JsonInput.BoolFieldCamelCaseTrue
+Recommended.JsonInput.BoolFieldDoubleQuotedFalse
+Recommended.JsonInput.BoolFieldDoubleQuotedTrue
+Recommended.JsonInput.BoolMapFieldKeyNotQuoted
+Recommended.JsonInput.DoubleFieldInfinityNotQuoted
+Recommended.JsonInput.DoubleFieldNanNotQuoted
+Recommended.JsonInput.DoubleFieldNegativeInfinityNotQuoted
+Recommended.JsonInput.FieldMaskInvalidCharacter
+Recommended.JsonInput.FieldNameDuplicate
+Recommended.JsonInput.FieldNameNotQuoted
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.JsonOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.ProtobufOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.Validator
+Recommended.JsonInput.FloatFieldInfinityNotQuoted
+Recommended.JsonInput.FloatFieldNanNotQuoted
+Recommended.JsonInput.FloatFieldNegativeInfinityNotQuoted
+Recommended.JsonInput.Int32MapFieldKeyNotQuoted
+Recommended.JsonInput.Int64MapFieldKeyNotQuoted
+Recommended.JsonInput.JsonWithComments
+Recommended.JsonInput.StringFieldSingleQuoteBoth
+Recommended.JsonInput.StringFieldSingleQuoteKey
+Recommended.JsonInput.StringFieldSingleQuoteValue
+Recommended.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.JsonInput.Uint32MapFieldKeyNotQuoted
+Recommended.JsonInput.Uint64MapFieldKeyNotQuoted
+Required.JsonInput.EnumFieldNotQuoted
+Required.JsonInput.FieldNameInLowerCamelCase.Validator
+Required.JsonInput.FieldNameInSnakeCase.JsonOutput
+Required.JsonInput.FieldNameInSnakeCase.ProtobufOutput
+Required.JsonInput.Int32FieldLeadingZero
+Required.JsonInput.Int32FieldNegativeWithLeadingZero
+Required.JsonInput.Int32FieldPlusSign
+Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotBool
+Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
+Required.JsonInput.StringFieldNotAString
diff --git a/conformance/failure_list_objc.txt b/conformance/failure_list_objc.txt
index 5dac3501..dd538c10 100644
--- a/conformance/failure_list_objc.txt
+++ b/conformance/failure_list_objc.txt
@@ -1,4 +1,4 @@
-# No tests currently failing.
+# All tests currently passing.
#
-# json input or output tests are skipped (in conformance_objc.m) as mobile
-# platforms don't support json wire format to avoid code bloat.
+# JSON input or output tests are skipped (in conformance_objc.m) as mobile
+# platforms don't support JSON wire format to avoid code bloat.
diff --git a/conformance/failure_list_python.txt b/conformance/failure_list_python.txt
index 550a043f..04985199 100644
--- a/conformance/failure_list_python.txt
+++ b/conformance/failure_list_python.txt
@@ -1,47 +1,19 @@
-DurationProtoInputTooLarge.JsonOutput
-DurationProtoInputTooSmall.JsonOutput
-FieldMaskNumbersDontRoundTrip.JsonOutput
-FieldMaskPathsDontRoundTrip.JsonOutput
-FieldMaskTooManyUnderscore.JsonOutput
-JsonInput.AnyWithFieldMask.ProtobufOutput
-JsonInput.BytesFieldInvalidBase64Characters
-JsonInput.DoubleFieldInfinityNotQuoted
-JsonInput.DoubleFieldNanNotQuoted
-JsonInput.DoubleFieldNegativeInfinityNotQuoted
-JsonInput.DoubleFieldTooSmall
-JsonInput.DurationJsonInputTooLarge
-JsonInput.DurationJsonInputTooSmall
-JsonInput.DurationMissingS
-JsonInput.EnumFieldNumericValueNonZero.JsonOutput
-JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
-JsonInput.EnumFieldNumericValueZero.JsonOutput
-JsonInput.EnumFieldNumericValueZero.ProtobufOutput
-JsonInput.EnumFieldUnknownValue.Validator
-JsonInput.FieldMask.ProtobufOutput
-JsonInput.FieldMaskInvalidCharacter
-JsonInput.FieldNameInLowerCamelCase.Validator
-JsonInput.FieldNameInSnakeCase.JsonOutput
-JsonInput.FieldNameInSnakeCase.ProtobufOutput
-JsonInput.FloatFieldInfinityNotQuoted
-JsonInput.FloatFieldNanNotQuoted
-JsonInput.FloatFieldNegativeInfinityNotQuoted
-JsonInput.FloatFieldTooLarge
-JsonInput.FloatFieldTooSmall
-JsonInput.Int32FieldExponentialFormat.JsonOutput
-JsonInput.Int32FieldExponentialFormat.ProtobufOutput
-JsonInput.Int32FieldFloatTrailingZero.JsonOutput
-JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
-JsonInput.Int32FieldMaxFloatValue.JsonOutput
-JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
-JsonInput.Int32FieldMinFloatValue.JsonOutput
-JsonInput.Int32FieldMinFloatValue.ProtobufOutput
-JsonInput.OriginalProtoFieldName.JsonOutput
-JsonInput.OriginalProtoFieldName.ProtobufOutput
-JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
-JsonInput.TimestampJsonInputLowercaseT
-JsonInput.Uint32FieldMaxFloatValue.JsonOutput
-JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
-JsonInput.ValueAcceptNull.JsonOutput
-JsonInput.ValueAcceptNull.ProtobufOutput
-TimestampProtoInputTooLarge.JsonOutput
-TimestampProtoInputTooSmall.JsonOutput
+Recommended.JsonInput.DoubleFieldInfinityNotQuoted
+Recommended.JsonInput.DoubleFieldNanNotQuoted
+Recommended.JsonInput.DoubleFieldNegativeInfinityNotQuoted
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.JsonOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.ProtobufOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.Validator
+Recommended.JsonInput.FloatFieldInfinityNotQuoted
+Recommended.JsonInput.FloatFieldNanNotQuoted
+Recommended.JsonInput.FloatFieldNegativeInfinityNotQuoted
+Required.JsonInput.BytesFieldInvalidBase64Characters
+Required.JsonInput.DoubleFieldTooSmall
+Required.JsonInput.EnumFieldUnknownValue.Validator
+Required.JsonInput.FieldNameInLowerCamelCase.Validator
+Required.JsonInput.FieldNameInSnakeCase.JsonOutput
+Required.JsonInput.FieldNameInSnakeCase.ProtobufOutput
+Required.JsonInput.FloatFieldTooLarge
+Required.JsonInput.FloatFieldTooSmall
+Required.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
+Required.JsonInput.TimestampJsonInputLowercaseT
diff --git a/conformance/failure_list_python_cpp.txt b/conformance/failure_list_python_cpp.txt
index 1eb916ab..f3958f5f 100644
--- a/conformance/failure_list_python_cpp.txt
+++ b/conformance/failure_list_python_cpp.txt
@@ -7,66 +7,38 @@
# TODO(haberman): insert links to corresponding bugs tracking the issue.
# Should we use GitHub issues or the Google-internal bug tracker?
-DurationProtoInputTooLarge.JsonOutput
-DurationProtoInputTooSmall.JsonOutput
-FieldMaskNumbersDontRoundTrip.JsonOutput
-FieldMaskPathsDontRoundTrip.JsonOutput
-FieldMaskTooManyUnderscore.JsonOutput
-JsonInput.AnyWithFieldMask.ProtobufOutput
-JsonInput.BytesFieldInvalidBase64Characters
-JsonInput.DoubleFieldInfinityNotQuoted
-JsonInput.DoubleFieldNanNotQuoted
-JsonInput.DoubleFieldNegativeInfinityNotQuoted
-JsonInput.DoubleFieldTooSmall
-JsonInput.DurationJsonInputTooLarge
-JsonInput.DurationJsonInputTooSmall
-JsonInput.DurationMissingS
-JsonInput.EnumFieldNumericValueNonZero.JsonOutput
-JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
-JsonInput.EnumFieldNumericValueZero.JsonOutput
-JsonInput.EnumFieldNumericValueZero.ProtobufOutput
-JsonInput.EnumFieldUnknownValue.Validator
-JsonInput.FieldMask.ProtobufOutput
-JsonInput.FieldMaskInvalidCharacter
-JsonInput.FieldNameInLowerCamelCase.Validator
-JsonInput.FieldNameInSnakeCase.JsonOutput
-JsonInput.FieldNameInSnakeCase.ProtobufOutput
-JsonInput.FloatFieldInfinityNotQuoted
-JsonInput.FloatFieldNanNotQuoted
-JsonInput.FloatFieldNegativeInfinityNotQuoted
-JsonInput.FloatFieldTooLarge
-JsonInput.FloatFieldTooSmall
-JsonInput.Int32FieldExponentialFormat.JsonOutput
-JsonInput.Int32FieldExponentialFormat.ProtobufOutput
-JsonInput.Int32FieldFloatTrailingZero.JsonOutput
-JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
-JsonInput.Int32FieldMaxFloatValue.JsonOutput
-JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
-JsonInput.Int32FieldMinFloatValue.JsonOutput
-JsonInput.Int32FieldMinFloatValue.ProtobufOutput
-JsonInput.OriginalProtoFieldName.JsonOutput
-JsonInput.OriginalProtoFieldName.ProtobufOutput
-JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
-JsonInput.TimestampJsonInputLowercaseT
-JsonInput.Uint32FieldMaxFloatValue.JsonOutput
-JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
-JsonInput.ValueAcceptNull.JsonOutput
-JsonInput.ValueAcceptNull.ProtobufOutput
-ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
-ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
-ProtobufInput.PrematureEofInPackedField.BOOL
-ProtobufInput.PrematureEofInPackedField.DOUBLE
-ProtobufInput.PrematureEofInPackedField.ENUM
-ProtobufInput.PrematureEofInPackedField.FIXED32
-ProtobufInput.PrematureEofInPackedField.FIXED64
-ProtobufInput.PrematureEofInPackedField.FLOAT
-ProtobufInput.PrematureEofInPackedField.INT32
-ProtobufInput.PrematureEofInPackedField.INT64
-ProtobufInput.PrematureEofInPackedField.SFIXED32
-ProtobufInput.PrematureEofInPackedField.SFIXED64
-ProtobufInput.PrematureEofInPackedField.SINT32
-ProtobufInput.PrematureEofInPackedField.SINT64
-ProtobufInput.PrematureEofInPackedField.UINT32
-ProtobufInput.PrematureEofInPackedField.UINT64
-TimestampProtoInputTooLarge.JsonOutput
-TimestampProtoInputTooSmall.JsonOutput
+Recommended.JsonInput.DoubleFieldInfinityNotQuoted
+Recommended.JsonInput.DoubleFieldNanNotQuoted
+Recommended.JsonInput.DoubleFieldNegativeInfinityNotQuoted
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.JsonOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.ProtobufOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.Validator
+Recommended.JsonInput.FloatFieldInfinityNotQuoted
+Recommended.JsonInput.FloatFieldNanNotQuoted
+Recommended.JsonInput.FloatFieldNegativeInfinityNotQuoted
+Required.JsonInput.BytesFieldInvalidBase64Characters
+Required.JsonInput.DoubleFieldTooSmall
+Required.JsonInput.EnumFieldUnknownValue.Validator
+Required.JsonInput.FieldNameInLowerCamelCase.Validator
+Required.JsonInput.FieldNameInSnakeCase.JsonOutput
+Required.JsonInput.FieldNameInSnakeCase.ProtobufOutput
+Required.JsonInput.FloatFieldTooLarge
+Required.JsonInput.FloatFieldTooSmall
+Required.JsonInput.RepeatedFieldWrongElementTypeExpectingIntegersGotBool
+Required.JsonInput.TimestampJsonInputLowercaseT
+Required.ProtobufInput.PrematureEofInDelimitedDataForKnownNonRepeatedValue.MESSAGE
+Required.ProtobufInput.PrematureEofInDelimitedDataForKnownRepeatedValue.MESSAGE
+Required.ProtobufInput.PrematureEofInPackedField.BOOL
+Required.ProtobufInput.PrematureEofInPackedField.DOUBLE
+Required.ProtobufInput.PrematureEofInPackedField.ENUM
+Required.ProtobufInput.PrematureEofInPackedField.FIXED32
+Required.ProtobufInput.PrematureEofInPackedField.FIXED64
+Required.ProtobufInput.PrematureEofInPackedField.FLOAT
+Required.ProtobufInput.PrematureEofInPackedField.INT32
+Required.ProtobufInput.PrematureEofInPackedField.INT64
+Required.ProtobufInput.PrematureEofInPackedField.SFIXED32
+Required.ProtobufInput.PrematureEofInPackedField.SFIXED64
+Required.ProtobufInput.PrematureEofInPackedField.SINT32
+Required.ProtobufInput.PrematureEofInPackedField.SINT64
+Required.ProtobufInput.PrematureEofInPackedField.UINT32
+Required.ProtobufInput.PrematureEofInPackedField.UINT64
diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt
index 7c12da06..dbd55697 100644
--- a/conformance/failure_list_ruby.txt
+++ b/conformance/failure_list_ruby.txt
@@ -1,199 +1,209 @@
-DurationProtoInputTooLarge.JsonOutput
-DurationProtoInputTooSmall.JsonOutput
-FieldMaskNumbersDontRoundTrip.JsonOutput
-FieldMaskPathsDontRoundTrip.JsonOutput
-FieldMaskTooManyUnderscore.JsonOutput
-JsonInput.Any.JsonOutput
-JsonInput.Any.ProtobufOutput
-JsonInput.AnyNested.JsonOutput
-JsonInput.AnyNested.ProtobufOutput
-JsonInput.AnyUnorderedTypeTag.JsonOutput
-JsonInput.AnyUnorderedTypeTag.ProtobufOutput
-JsonInput.AnyWithDuration.JsonOutput
-JsonInput.AnyWithDuration.ProtobufOutput
-JsonInput.AnyWithFieldMask.JsonOutput
-JsonInput.AnyWithFieldMask.ProtobufOutput
-JsonInput.AnyWithInt32ValueWrapper.JsonOutput
-JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
-JsonInput.AnyWithStruct.JsonOutput
-JsonInput.AnyWithStruct.ProtobufOutput
-JsonInput.AnyWithTimestamp.JsonOutput
-JsonInput.AnyWithTimestamp.ProtobufOutput
-JsonInput.AnyWithValueForInteger.JsonOutput
-JsonInput.AnyWithValueForInteger.ProtobufOutput
-JsonInput.AnyWithValueForJsonObject.JsonOutput
-JsonInput.AnyWithValueForJsonObject.ProtobufOutput
-JsonInput.BoolFieldIntegerOne
-JsonInput.BoolFieldIntegerZero
-JsonInput.DoubleFieldInfinity.JsonOutput
-JsonInput.DoubleFieldInfinity.ProtobufOutput
-JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
-JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
-JsonInput.DoubleFieldMaxPositiveValue.JsonOutput
-JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput
-JsonInput.DoubleFieldMinNegativeValue.JsonOutput
-JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput
-JsonInput.DoubleFieldMinPositiveValue.JsonOutput
-JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
-JsonInput.DoubleFieldNan.JsonOutput
-JsonInput.DoubleFieldNan.ProtobufOutput
-JsonInput.DoubleFieldNegativeInfinity.JsonOutput
-JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput
-JsonInput.DoubleFieldQuotedValue.JsonOutput
-JsonInput.DoubleFieldQuotedValue.ProtobufOutput
-JsonInput.DurationHas3FractionalDigits.Validator
-JsonInput.DurationHas6FractionalDigits.Validator
-JsonInput.DurationHas9FractionalDigits.Validator
-JsonInput.DurationHasZeroFractionalDigit.Validator
-JsonInput.DurationMaxValue.JsonOutput
-JsonInput.DurationMaxValue.ProtobufOutput
-JsonInput.DurationMinValue.JsonOutput
-JsonInput.DurationMinValue.ProtobufOutput
-JsonInput.DurationRepeatedValue.JsonOutput
-JsonInput.DurationRepeatedValue.ProtobufOutput
-JsonInput.EnumFieldNumericValueNonZero.JsonOutput
-JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
-JsonInput.EnumFieldNumericValueZero.JsonOutput
-JsonInput.EnumFieldNumericValueZero.ProtobufOutput
-JsonInput.EnumFieldUnknownValue.Validator
-JsonInput.FieldMask.JsonOutput
-JsonInput.FieldMask.ProtobufOutput
-JsonInput.FieldNameInSnakeCase.JsonOutput
-JsonInput.FieldNameWithMixedCases.JsonOutput
-JsonInput.FieldNameWithMixedCases.ProtobufOutput
-JsonInput.FieldNameWithMixedCases.Validator
-JsonInput.FloatFieldInfinity.JsonOutput
-JsonInput.FloatFieldInfinity.ProtobufOutput
-JsonInput.FloatFieldNan.JsonOutput
-JsonInput.FloatFieldNan.ProtobufOutput
-JsonInput.FloatFieldNegativeInfinity.JsonOutput
-JsonInput.FloatFieldNegativeInfinity.ProtobufOutput
-JsonInput.FloatFieldQuotedValue.JsonOutput
-JsonInput.FloatFieldQuotedValue.ProtobufOutput
-JsonInput.FloatFieldTooLarge
-JsonInput.FloatFieldTooSmall
-JsonInput.Int32FieldExponentialFormat.JsonOutput
-JsonInput.Int32FieldExponentialFormat.ProtobufOutput
-JsonInput.Int32FieldFloatTrailingZero.JsonOutput
-JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
-JsonInput.Int32FieldMaxFloatValue.JsonOutput
-JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
-JsonInput.Int32FieldMinFloatValue.JsonOutput
-JsonInput.Int32FieldMinFloatValue.ProtobufOutput
-JsonInput.Int32FieldStringValue.JsonOutput
-JsonInput.Int32FieldStringValue.ProtobufOutput
-JsonInput.Int32FieldStringValueEscaped.JsonOutput
-JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
-JsonInput.Int32MapEscapedKey.JsonOutput
-JsonInput.Int32MapEscapedKey.ProtobufOutput
-JsonInput.Int32MapField.JsonOutput
-JsonInput.Int32MapField.ProtobufOutput
-JsonInput.Int64FieldBeString.Validator
-JsonInput.Int64FieldMaxValue.JsonOutput
-JsonInput.Int64FieldMaxValue.ProtobufOutput
-JsonInput.Int64FieldMinValue.JsonOutput
-JsonInput.Int64FieldMinValue.ProtobufOutput
-JsonInput.Int64MapEscapedKey.JsonOutput
-JsonInput.Int64MapEscapedKey.ProtobufOutput
-JsonInput.Int64MapField.JsonOutput
-JsonInput.Int64MapField.ProtobufOutput
-JsonInput.MessageField.JsonOutput
-JsonInput.MessageField.ProtobufOutput
-JsonInput.MessageMapField.JsonOutput
-JsonInput.MessageMapField.ProtobufOutput
-JsonInput.MessageRepeatedField.JsonOutput
-JsonInput.MessageRepeatedField.ProtobufOutput
-JsonInput.OptionalBoolWrapper.JsonOutput
-JsonInput.OptionalBoolWrapper.ProtobufOutput
-JsonInput.OptionalBytesWrapper.JsonOutput
-JsonInput.OptionalBytesWrapper.ProtobufOutput
-JsonInput.OptionalDoubleWrapper.JsonOutput
-JsonInput.OptionalDoubleWrapper.ProtobufOutput
-JsonInput.OptionalFloatWrapper.JsonOutput
-JsonInput.OptionalFloatWrapper.ProtobufOutput
-JsonInput.OptionalInt32Wrapper.JsonOutput
-JsonInput.OptionalInt32Wrapper.ProtobufOutput
-JsonInput.OptionalInt64Wrapper.JsonOutput
-JsonInput.OptionalInt64Wrapper.ProtobufOutput
-JsonInput.OptionalStringWrapper.JsonOutput
-JsonInput.OptionalStringWrapper.ProtobufOutput
-JsonInput.OptionalUint32Wrapper.JsonOutput
-JsonInput.OptionalUint32Wrapper.ProtobufOutput
-JsonInput.OptionalUint64Wrapper.JsonOutput
-JsonInput.OptionalUint64Wrapper.ProtobufOutput
-JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
-JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
-JsonInput.OriginalProtoFieldName.JsonOutput
-JsonInput.PrimitiveRepeatedField.JsonOutput
-JsonInput.PrimitiveRepeatedField.ProtobufOutput
-JsonInput.RepeatedBoolWrapper.JsonOutput
-JsonInput.RepeatedBoolWrapper.ProtobufOutput
-JsonInput.RepeatedBytesWrapper.JsonOutput
-JsonInput.RepeatedBytesWrapper.ProtobufOutput
-JsonInput.RepeatedDoubleWrapper.JsonOutput
-JsonInput.RepeatedDoubleWrapper.ProtobufOutput
-JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
-JsonInput.RepeatedFloatWrapper.JsonOutput
-JsonInput.RepeatedFloatWrapper.ProtobufOutput
-JsonInput.RepeatedInt32Wrapper.JsonOutput
-JsonInput.RepeatedInt32Wrapper.ProtobufOutput
-JsonInput.RepeatedInt64Wrapper.JsonOutput
-JsonInput.RepeatedInt64Wrapper.ProtobufOutput
-JsonInput.RepeatedStringWrapper.JsonOutput
-JsonInput.RepeatedStringWrapper.ProtobufOutput
-JsonInput.RepeatedUint32Wrapper.JsonOutput
-JsonInput.RepeatedUint32Wrapper.ProtobufOutput
-JsonInput.RepeatedUint64Wrapper.JsonOutput
-JsonInput.RepeatedUint64Wrapper.ProtobufOutput
-JsonInput.StringFieldNotAString
-JsonInput.StringFieldSurrogateInWrongOrder
-JsonInput.StringFieldSurrogatePair.JsonOutput
-JsonInput.StringFieldSurrogatePair.ProtobufOutput
-JsonInput.StringFieldUnpairedHighSurrogate
-JsonInput.StringFieldUnpairedLowSurrogate
-JsonInput.Struct.JsonOutput
-JsonInput.Struct.ProtobufOutput
-JsonInput.TimestampHas3FractionalDigits.Validator
-JsonInput.TimestampHas6FractionalDigits.Validator
-JsonInput.TimestampHas9FractionalDigits.Validator
-JsonInput.TimestampHasZeroFractionalDigit.Validator
-JsonInput.TimestampMaxValue.JsonOutput
-JsonInput.TimestampMaxValue.ProtobufOutput
-JsonInput.TimestampMinValue.JsonOutput
-JsonInput.TimestampMinValue.ProtobufOutput
-JsonInput.TimestampRepeatedValue.JsonOutput
-JsonInput.TimestampRepeatedValue.ProtobufOutput
-JsonInput.TimestampWithNegativeOffset.JsonOutput
-JsonInput.TimestampWithNegativeOffset.ProtobufOutput
-JsonInput.TimestampWithPositiveOffset.JsonOutput
-JsonInput.TimestampWithPositiveOffset.ProtobufOutput
-JsonInput.TimestampZeroNormalized.Validator
-JsonInput.Uint32FieldMaxFloatValue.JsonOutput
-JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
-JsonInput.Uint32MapField.JsonOutput
-JsonInput.Uint32MapField.ProtobufOutput
-JsonInput.Uint64FieldBeString.Validator
-JsonInput.Uint64FieldMaxValue.JsonOutput
-JsonInput.Uint64FieldMaxValue.ProtobufOutput
-JsonInput.Uint64MapField.JsonOutput
-JsonInput.Uint64MapField.ProtobufOutput
-JsonInput.ValueAcceptBool.JsonOutput
-JsonInput.ValueAcceptBool.ProtobufOutput
-JsonInput.ValueAcceptFloat.JsonOutput
-JsonInput.ValueAcceptFloat.ProtobufOutput
-JsonInput.ValueAcceptInteger.JsonOutput
-JsonInput.ValueAcceptInteger.ProtobufOutput
-JsonInput.ValueAcceptList.JsonOutput
-JsonInput.ValueAcceptList.ProtobufOutput
-JsonInput.ValueAcceptNull.JsonOutput
-JsonInput.ValueAcceptNull.ProtobufOutput
-JsonInput.ValueAcceptObject.JsonOutput
-JsonInput.ValueAcceptObject.ProtobufOutput
-JsonInput.ValueAcceptString.JsonOutput
-JsonInput.ValueAcceptString.ProtobufOutput
-ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
-ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
-ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
-ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
-TimestampProtoInputTooLarge.JsonOutput
-TimestampProtoInputTooSmall.JsonOutput
+Recommended.FieldMaskNumbersDontRoundTrip.JsonOutput
+Recommended.FieldMaskPathsDontRoundTrip.JsonOutput
+Recommended.FieldMaskTooManyUnderscore.JsonOutput
+Recommended.JsonInput.BoolFieldIntegerOne
+Recommended.JsonInput.BoolFieldIntegerZero
+Recommended.JsonInput.DurationHas3FractionalDigits.Validator
+Recommended.JsonInput.DurationHas6FractionalDigits.Validator
+Recommended.JsonInput.DurationHas9FractionalDigits.Validator
+Recommended.JsonInput.DurationHasZeroFractionalDigit.Validator
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.JsonOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.ProtobufOutput
+Recommended.JsonInput.FieldNameWithDoubleUnderscores.Validator
+Recommended.JsonInput.Int64FieldBeString.Validator
+Recommended.JsonInput.OneofZeroDouble.JsonOutput
+Recommended.JsonInput.OneofZeroDouble.ProtobufOutput
+Recommended.JsonInput.OneofZeroFloat.JsonOutput
+Recommended.JsonInput.OneofZeroFloat.ProtobufOutput
+Recommended.JsonInput.OneofZeroUint32.JsonOutput
+Recommended.JsonInput.OneofZeroUint32.ProtobufOutput
+Recommended.JsonInput.OneofZeroUint64.JsonOutput
+Recommended.JsonInput.OneofZeroUint64.ProtobufOutput
+Recommended.JsonInput.StringEndsWithEscapeChar
+Recommended.JsonInput.StringFieldSurrogateInWrongOrder
+Recommended.JsonInput.StringFieldUnpairedHighSurrogate
+Recommended.JsonInput.StringFieldUnpairedLowSurrogate
+Recommended.JsonInput.TimestampHas3FractionalDigits.Validator
+Recommended.JsonInput.TimestampHas6FractionalDigits.Validator
+Recommended.JsonInput.TimestampHas9FractionalDigits.Validator
+Recommended.JsonInput.TimestampHasZeroFractionalDigit.Validator
+Recommended.JsonInput.TimestampZeroNormalized.Validator
+Recommended.JsonInput.Uint64FieldBeString.Validator
+Required.DurationProtoInputTooLarge.JsonOutput
+Required.DurationProtoInputTooSmall.JsonOutput
+Required.JsonInput.Any.JsonOutput
+Required.JsonInput.Any.ProtobufOutput
+Required.JsonInput.AnyNested.JsonOutput
+Required.JsonInput.AnyNested.ProtobufOutput
+Required.JsonInput.AnyUnorderedTypeTag.JsonOutput
+Required.JsonInput.AnyUnorderedTypeTag.ProtobufOutput
+Required.JsonInput.AnyWithDuration.JsonOutput
+Required.JsonInput.AnyWithDuration.ProtobufOutput
+Required.JsonInput.AnyWithFieldMask.JsonOutput
+Required.JsonInput.AnyWithFieldMask.ProtobufOutput
+Required.JsonInput.AnyWithInt32ValueWrapper.JsonOutput
+Required.JsonInput.AnyWithInt32ValueWrapper.ProtobufOutput
+Required.JsonInput.AnyWithStruct.JsonOutput
+Required.JsonInput.AnyWithStruct.ProtobufOutput
+Required.JsonInput.AnyWithTimestamp.JsonOutput
+Required.JsonInput.AnyWithTimestamp.ProtobufOutput
+Required.JsonInput.AnyWithValueForInteger.JsonOutput
+Required.JsonInput.AnyWithValueForInteger.ProtobufOutput
+Required.JsonInput.AnyWithValueForJsonObject.JsonOutput
+Required.JsonInput.AnyWithValueForJsonObject.ProtobufOutput
+Required.JsonInput.DoubleFieldInfinity.JsonOutput
+Required.JsonInput.DoubleFieldInfinity.ProtobufOutput
+Required.JsonInput.DoubleFieldMaxNegativeValue.JsonOutput
+Required.JsonInput.DoubleFieldMaxNegativeValue.ProtobufOutput
+Required.JsonInput.DoubleFieldMaxPositiveValue.JsonOutput
+Required.JsonInput.DoubleFieldMaxPositiveValue.ProtobufOutput
+Required.JsonInput.DoubleFieldMinNegativeValue.JsonOutput
+Required.JsonInput.DoubleFieldMinNegativeValue.ProtobufOutput
+Required.JsonInput.DoubleFieldMinPositiveValue.JsonOutput
+Required.JsonInput.DoubleFieldMinPositiveValue.ProtobufOutput
+Required.JsonInput.DoubleFieldNan.JsonOutput
+Required.JsonInput.DoubleFieldNan.ProtobufOutput
+Required.JsonInput.DoubleFieldNegativeInfinity.JsonOutput
+Required.JsonInput.DoubleFieldNegativeInfinity.ProtobufOutput
+Required.JsonInput.DoubleFieldQuotedValue.JsonOutput
+Required.JsonInput.DoubleFieldQuotedValue.ProtobufOutput
+Required.JsonInput.DurationMaxValue.JsonOutput
+Required.JsonInput.DurationMaxValue.ProtobufOutput
+Required.JsonInput.DurationMinValue.JsonOutput
+Required.JsonInput.DurationMinValue.ProtobufOutput
+Required.JsonInput.DurationRepeatedValue.JsonOutput
+Required.JsonInput.DurationRepeatedValue.ProtobufOutput
+Required.JsonInput.EnumFieldNumericValueNonZero.JsonOutput
+Required.JsonInput.EnumFieldNumericValueNonZero.ProtobufOutput
+Required.JsonInput.EnumFieldNumericValueZero.JsonOutput
+Required.JsonInput.EnumFieldNumericValueZero.ProtobufOutput
+Required.JsonInput.EnumFieldUnknownValue.Validator
+Required.JsonInput.FieldMask.JsonOutput
+Required.JsonInput.FieldMask.ProtobufOutput
+Required.JsonInput.FieldNameInLowerCamelCase.Validator
+Required.JsonInput.FieldNameInSnakeCase.JsonOutput
+Required.JsonInput.FieldNameInSnakeCase.ProtobufOutput
+Required.JsonInput.FloatFieldInfinity.JsonOutput
+Required.JsonInput.FloatFieldInfinity.ProtobufOutput
+Required.JsonInput.FloatFieldNan.JsonOutput
+Required.JsonInput.FloatFieldNan.ProtobufOutput
+Required.JsonInput.FloatFieldNegativeInfinity.JsonOutput
+Required.JsonInput.FloatFieldNegativeInfinity.ProtobufOutput
+Required.JsonInput.FloatFieldQuotedValue.JsonOutput
+Required.JsonInput.FloatFieldQuotedValue.ProtobufOutput
+Required.JsonInput.FloatFieldTooLarge
+Required.JsonInput.FloatFieldTooSmall
+Required.JsonInput.Int32FieldExponentialFormat.JsonOutput
+Required.JsonInput.Int32FieldExponentialFormat.ProtobufOutput
+Required.JsonInput.Int32FieldFloatTrailingZero.JsonOutput
+Required.JsonInput.Int32FieldFloatTrailingZero.ProtobufOutput
+Required.JsonInput.Int32FieldMaxFloatValue.JsonOutput
+Required.JsonInput.Int32FieldMaxFloatValue.ProtobufOutput
+Required.JsonInput.Int32FieldMinFloatValue.JsonOutput
+Required.JsonInput.Int32FieldMinFloatValue.ProtobufOutput
+Required.JsonInput.Int32FieldStringValue.JsonOutput
+Required.JsonInput.Int32FieldStringValue.ProtobufOutput
+Required.JsonInput.Int32FieldStringValueEscaped.JsonOutput
+Required.JsonInput.Int32FieldStringValueEscaped.ProtobufOutput
+Required.JsonInput.Int32MapEscapedKey.JsonOutput
+Required.JsonInput.Int32MapEscapedKey.ProtobufOutput
+Required.JsonInput.Int32MapField.JsonOutput
+Required.JsonInput.Int32MapField.ProtobufOutput
+Required.JsonInput.Int64FieldMaxValue.JsonOutput
+Required.JsonInput.Int64FieldMaxValue.ProtobufOutput
+Required.JsonInput.Int64FieldMinValue.JsonOutput
+Required.JsonInput.Int64FieldMinValue.ProtobufOutput
+Required.JsonInput.Int64MapEscapedKey.JsonOutput
+Required.JsonInput.Int64MapEscapedKey.ProtobufOutput
+Required.JsonInput.Int64MapField.JsonOutput
+Required.JsonInput.Int64MapField.ProtobufOutput
+Required.JsonInput.MessageField.JsonOutput
+Required.JsonInput.MessageField.ProtobufOutput
+Required.JsonInput.MessageMapField.JsonOutput
+Required.JsonInput.MessageMapField.ProtobufOutput
+Required.JsonInput.MessageRepeatedField.JsonOutput
+Required.JsonInput.MessageRepeatedField.ProtobufOutput
+Required.JsonInput.OptionalBoolWrapper.JsonOutput
+Required.JsonInput.OptionalBoolWrapper.ProtobufOutput
+Required.JsonInput.OptionalBytesWrapper.JsonOutput
+Required.JsonInput.OptionalBytesWrapper.ProtobufOutput
+Required.JsonInput.OptionalDoubleWrapper.JsonOutput
+Required.JsonInput.OptionalDoubleWrapper.ProtobufOutput
+Required.JsonInput.OptionalFloatWrapper.JsonOutput
+Required.JsonInput.OptionalFloatWrapper.ProtobufOutput
+Required.JsonInput.OptionalInt32Wrapper.JsonOutput
+Required.JsonInput.OptionalInt32Wrapper.ProtobufOutput
+Required.JsonInput.OptionalInt64Wrapper.JsonOutput
+Required.JsonInput.OptionalInt64Wrapper.ProtobufOutput
+Required.JsonInput.OptionalStringWrapper.JsonOutput
+Required.JsonInput.OptionalStringWrapper.ProtobufOutput
+Required.JsonInput.OptionalUint32Wrapper.JsonOutput
+Required.JsonInput.OptionalUint32Wrapper.ProtobufOutput
+Required.JsonInput.OptionalUint64Wrapper.JsonOutput
+Required.JsonInput.OptionalUint64Wrapper.ProtobufOutput
+Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.JsonOutput
+Required.JsonInput.OptionalWrapperTypesWithNonDefaultValue.ProtobufOutput
+Required.JsonInput.PrimitiveRepeatedField.JsonOutput
+Required.JsonInput.PrimitiveRepeatedField.ProtobufOutput
+Required.JsonInput.RepeatedBoolWrapper.JsonOutput
+Required.JsonInput.RepeatedBoolWrapper.ProtobufOutput
+Required.JsonInput.RepeatedBytesWrapper.JsonOutput
+Required.JsonInput.RepeatedBytesWrapper.ProtobufOutput
+Required.JsonInput.RepeatedDoubleWrapper.JsonOutput
+Required.JsonInput.RepeatedDoubleWrapper.ProtobufOutput
+Required.JsonInput.RepeatedFieldWrongElementTypeExpectingStringsGotInt
+Required.JsonInput.RepeatedFloatWrapper.JsonOutput
+Required.JsonInput.RepeatedFloatWrapper.ProtobufOutput
+Required.JsonInput.RepeatedInt32Wrapper.JsonOutput
+Required.JsonInput.RepeatedInt32Wrapper.ProtobufOutput
+Required.JsonInput.RepeatedInt64Wrapper.JsonOutput
+Required.JsonInput.RepeatedInt64Wrapper.ProtobufOutput
+Required.JsonInput.RepeatedStringWrapper.JsonOutput
+Required.JsonInput.RepeatedStringWrapper.ProtobufOutput
+Required.JsonInput.RepeatedUint32Wrapper.JsonOutput
+Required.JsonInput.RepeatedUint32Wrapper.ProtobufOutput
+Required.JsonInput.RepeatedUint64Wrapper.JsonOutput
+Required.JsonInput.RepeatedUint64Wrapper.ProtobufOutput
+Required.JsonInput.StringFieldNotAString
+Required.JsonInput.StringFieldSurrogatePair.JsonOutput
+Required.JsonInput.StringFieldSurrogatePair.ProtobufOutput
+Required.JsonInput.Struct.JsonOutput
+Required.JsonInput.Struct.ProtobufOutput
+Required.JsonInput.TimestampMaxValue.JsonOutput
+Required.JsonInput.TimestampMaxValue.ProtobufOutput
+Required.JsonInput.TimestampMinValue.JsonOutput
+Required.JsonInput.TimestampMinValue.ProtobufOutput
+Required.JsonInput.TimestampRepeatedValue.JsonOutput
+Required.JsonInput.TimestampRepeatedValue.ProtobufOutput
+Required.JsonInput.TimestampWithNegativeOffset.JsonOutput
+Required.JsonInput.TimestampWithNegativeOffset.ProtobufOutput
+Required.JsonInput.TimestampWithPositiveOffset.JsonOutput
+Required.JsonInput.TimestampWithPositiveOffset.ProtobufOutput
+Required.JsonInput.Uint32FieldMaxFloatValue.JsonOutput
+Required.JsonInput.Uint32FieldMaxFloatValue.ProtobufOutput
+Required.JsonInput.Uint32MapField.JsonOutput
+Required.JsonInput.Uint32MapField.ProtobufOutput
+Required.JsonInput.Uint64FieldMaxValue.JsonOutput
+Required.JsonInput.Uint64FieldMaxValue.ProtobufOutput
+Required.JsonInput.Uint64MapField.JsonOutput
+Required.JsonInput.Uint64MapField.ProtobufOutput
+Required.JsonInput.ValueAcceptBool.JsonOutput
+Required.JsonInput.ValueAcceptBool.ProtobufOutput
+Required.JsonInput.ValueAcceptFloat.JsonOutput
+Required.JsonInput.ValueAcceptFloat.ProtobufOutput
+Required.JsonInput.ValueAcceptInteger.JsonOutput
+Required.JsonInput.ValueAcceptInteger.ProtobufOutput
+Required.JsonInput.ValueAcceptList.JsonOutput
+Required.JsonInput.ValueAcceptList.ProtobufOutput
+Required.JsonInput.ValueAcceptNull.JsonOutput
+Required.JsonInput.ValueAcceptNull.ProtobufOutput
+Required.JsonInput.ValueAcceptObject.JsonOutput
+Required.JsonInput.ValueAcceptObject.ProtobufOutput
+Required.JsonInput.ValueAcceptString.JsonOutput
+Required.JsonInput.ValueAcceptString.ProtobufOutput
+Required.ProtobufInput.DoubleFieldNormalizeQuietNan.JsonOutput
+Required.ProtobufInput.DoubleFieldNormalizeSignalingNan.JsonOutput
+Required.ProtobufInput.FloatFieldNormalizeQuietNan.JsonOutput
+Required.ProtobufInput.FloatFieldNormalizeSignalingNan.JsonOutput
+Required.TimestampProtoInputTooLarge.JsonOutput
+Required.TimestampProtoInputTooSmall.JsonOutput
diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec
index 24b4a776..d079c683 100644
--- a/csharp/Google.Protobuf.Tools.nuspec
+++ b/csharp/Google.Protobuf.Tools.nuspec
@@ -5,7 +5,7 @@
<title>Google Protocol Buffers tools</title>
<summary>Tools for Protocol Buffers - Google's data interchange format.</summary>
<description>See project site for more info.</description>
- <version>3.0.0</version>
+ <version>3.1.0</version>
<authors>Google Inc.</authors>
<owners>protobuf-packages</owners>
<licenseUrl>https://github.com/google/protobuf/blob/master/LICENSE</licenseUrl>
diff --git a/csharp/README.md b/csharp/README.md
index ddf1d2be..ed5c7be7 100644
--- a/csharp/README.md
+++ b/csharp/README.md
@@ -1,8 +1,5 @@
This directory contains the C# Protocol Buffers runtime library.
-Status: Beta - ready for external testing
-=========================================
-
Usage
=====
diff --git a/csharp/build_tools.sh b/csharp/build_tools.sh
new file mode 100755
index 00000000..182c5c5c
--- /dev/null
+++ b/csharp/build_tools.sh
@@ -0,0 +1,52 @@
+#!/bin/bash
+
+if [ $# -ne 1 ]; then
+ cat <<EOF
+Usage: $0 <VERSION_NUMBER>
+
+Example:
+ $ $0 3.0.0
+
+This script will download pre-built protoc binaries from maven repository and
+create the Google.Protobuf.Tools package. Well-known type .proto files will also
+be included.
+EOF
+ exit 1
+fi
+
+VERSION_NUMBER=$1
+# <directory name> <binary file name> pairs.
+declare -a FILE_NAMES=( \
+ windows_x86 windows-x86_32.exe \
+ windows_x64 windows-x86_64.exe \
+ macosx_x86 osx-x86_32.exe \
+ macosx_x64 osx-x86_64.exe \
+ linux_x86 linux-x86_32.exe \
+ linux_x64 linux-x86_64.exe \
+)
+
+set -e
+
+mkdir -p protoc
+# Create a zip file for each binary.
+for((i=0;i<${#FILE_NAMES[@]};i+=2));do
+ DIR_NAME=${FILE_NAMES[$i]}
+ mkdir -p protoc/$DIR_NAME
+
+ if [ ${DIR_NAME:0:3} = "win" ]; then
+ TARGET_BINARY="protoc.exe"
+ else
+ TARGET_BINARY="protoc"
+ fi
+
+ BINARY_NAME=${FILE_NAMES[$(($i+1))]}
+ BINARY_URL=http://repo1.maven.org/maven2/com/google/protobuf/protoc/${VERSION_NUMBER}/protoc-${VERSION_NUMBER}-${BINARY_NAME}
+
+ if ! wget ${BINARY_URL} -O protoc/$DIR_NAME/$TARGET_BINARY &> /dev/null; then
+ echo "[ERROR] Failed to download ${BINARY_URL}" >&2
+ echo "[ERROR] Skipped $protoc-${VERSION_NAME}-${DIR_NAME}" >&2
+ continue
+ fi
+done
+
+nuget pack Google.Protobuf.Tools.nuspec
diff --git a/csharp/src/Google.Protobuf.Conformance/Conformance.cs b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
index 5fcbff7c..431ac4fb 100644
--- a/csharp/src/Google.Protobuf.Conformance/Conformance.cs
+++ b/csharp/src/Google.Protobuf.Conformance/Conformance.cs
@@ -34,7 +34,7 @@ namespace Conformance {
"IAEoCUgAEhkKD3NlcmlhbGl6ZV9lcnJvchgGIAEoCUgAEhcKDXJ1bnRpbWVf",
"ZXJyb3IYAiABKAlIABIaChBwcm90b2J1Zl9wYXlsb2FkGAMgASgMSAASFgoM",
"anNvbl9wYXlsb2FkGAQgASgJSAASEQoHc2tpcHBlZBgFIAEoCUgAQggKBnJl",
- "c3VsdCLVMgoMVGVzdEFsbFR5cGVzEhYKDm9wdGlvbmFsX2ludDMyGAEgASgF",
+ "c3VsdCKCNQoMVGVzdEFsbFR5cGVzEhYKDm9wdGlvbmFsX2ludDMyGAEgASgF",
"EhYKDm9wdGlvbmFsX2ludDY0GAIgASgDEhcKD29wdGlvbmFsX3VpbnQzMhgD",
"IAEoDRIXCg9vcHRpb25hbF91aW50NjQYBCABKAQSFwoPb3B0aW9uYWxfc2lu",
"dDMyGAUgASgREhcKD29wdGlvbmFsX3NpbnQ2NBgGIAEoEhIYChBvcHRpb25h",
@@ -102,93 +102,100 @@ namespace Conformance {
"TWFwU3RyaW5nRm9yZWlnbkVudW1FbnRyeRIWCgxvbmVvZl91aW50MzIYbyAB",
"KA1IABJHChRvbmVvZl9uZXN0ZWRfbWVzc2FnZRhwIAEoCzInLmNvbmZvcm1h",
"bmNlLlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlSAASFgoMb25lb2Zfc3Ry",
- "aW5nGHEgASgJSAASFQoLb25lb2ZfYnl0ZXMYciABKAxIABI6ChVvcHRpb25h",
- "bF9ib29sX3dyYXBwZXIYyQEgASgLMhouZ29vZ2xlLnByb3RvYnVmLkJvb2xW",
- "YWx1ZRI8ChZvcHRpb25hbF9pbnQzMl93cmFwcGVyGMoBIAEoCzIbLmdvb2ds",
- "ZS5wcm90b2J1Zi5JbnQzMlZhbHVlEjwKFm9wdGlvbmFsX2ludDY0X3dyYXBw",
- "ZXIYywEgASgLMhsuZ29vZ2xlLnByb3RvYnVmLkludDY0VmFsdWUSPgoXb3B0",
- "aW9uYWxfdWludDMyX3dyYXBwZXIYzAEgASgLMhwuZ29vZ2xlLnByb3RvYnVm",
- "LlVJbnQzMlZhbHVlEj4KF29wdGlvbmFsX3VpbnQ2NF93cmFwcGVyGM0BIAEo",
- "CzIcLmdvb2dsZS5wcm90b2J1Zi5VSW50NjRWYWx1ZRI8ChZvcHRpb25hbF9m",
- "bG9hdF93cmFwcGVyGM4BIAEoCzIbLmdvb2dsZS5wcm90b2J1Zi5GbG9hdFZh",
- "bHVlEj4KF29wdGlvbmFsX2RvdWJsZV93cmFwcGVyGM8BIAEoCzIcLmdvb2ds",
- "ZS5wcm90b2J1Zi5Eb3VibGVWYWx1ZRI+ChdvcHRpb25hbF9zdHJpbmdfd3Jh",
- "cHBlchjQASABKAsyHC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUSPAoW",
- "b3B0aW9uYWxfYnl0ZXNfd3JhcHBlchjRASABKAsyGy5nb29nbGUucHJvdG9i",
- "dWYuQnl0ZXNWYWx1ZRI6ChVyZXBlYXRlZF9ib29sX3dyYXBwZXIY0wEgAygL",
- "MhouZ29vZ2xlLnByb3RvYnVmLkJvb2xWYWx1ZRI8ChZyZXBlYXRlZF9pbnQz",
- "Ml93cmFwcGVyGNQBIAMoCzIbLmdvb2dsZS5wcm90b2J1Zi5JbnQzMlZhbHVl",
- "EjwKFnJlcGVhdGVkX2ludDY0X3dyYXBwZXIY1QEgAygLMhsuZ29vZ2xlLnBy",
- "b3RvYnVmLkludDY0VmFsdWUSPgoXcmVwZWF0ZWRfdWludDMyX3dyYXBwZXIY",
- "1gEgAygLMhwuZ29vZ2xlLnByb3RvYnVmLlVJbnQzMlZhbHVlEj4KF3JlcGVh",
- "dGVkX3VpbnQ2NF93cmFwcGVyGNcBIAMoCzIcLmdvb2dsZS5wcm90b2J1Zi5V",
- "SW50NjRWYWx1ZRI8ChZyZXBlYXRlZF9mbG9hdF93cmFwcGVyGNgBIAMoCzIb",
- "Lmdvb2dsZS5wcm90b2J1Zi5GbG9hdFZhbHVlEj4KF3JlcGVhdGVkX2RvdWJs",
- "ZV93cmFwcGVyGNkBIAMoCzIcLmdvb2dsZS5wcm90b2J1Zi5Eb3VibGVWYWx1",
- "ZRI+ChdyZXBlYXRlZF9zdHJpbmdfd3JhcHBlchjaASADKAsyHC5nb29nbGUu",
- "cHJvdG9idWYuU3RyaW5nVmFsdWUSPAoWcmVwZWF0ZWRfYnl0ZXNfd3JhcHBl",
- "chjbASADKAsyGy5nb29nbGUucHJvdG9idWYuQnl0ZXNWYWx1ZRI1ChFvcHRp",
- "b25hbF9kdXJhdGlvbhitAiABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRp",
- "b24SNwoSb3B0aW9uYWxfdGltZXN0YW1wGK4CIAEoCzIaLmdvb2dsZS5wcm90",
- "b2J1Zi5UaW1lc3RhbXASOAoTb3B0aW9uYWxfZmllbGRfbWFzaxivAiABKAsy",
- "Gi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrEjEKD29wdGlvbmFsX3N0cnVj",
- "dBiwAiABKAsyFy5nb29nbGUucHJvdG9idWYuU3RydWN0EisKDG9wdGlvbmFs",
- "X2FueRixAiABKAsyFC5nb29nbGUucHJvdG9idWYuQW55Ei8KDm9wdGlvbmFs",
- "X3ZhbHVlGLICIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRI1ChFyZXBl",
- "YXRlZF9kdXJhdGlvbhi3AiADKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRp",
- "b24SNwoScmVwZWF0ZWRfdGltZXN0YW1wGLgCIAMoCzIaLmdvb2dsZS5wcm90",
- "b2J1Zi5UaW1lc3RhbXASNwoScmVwZWF0ZWRfZmllbGRtYXNrGLkCIAMoCzIa",
- "Lmdvb2dsZS5wcm90b2J1Zi5GaWVsZE1hc2sSMQoPcmVwZWF0ZWRfc3RydWN0",
- "GMQCIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSKwoMcmVwZWF0ZWRf",
- "YW55GLsCIAMoCzIULmdvb2dsZS5wcm90b2J1Zi5BbnkSLwoOcmVwZWF0ZWRf",
- "dmFsdWUYvAIgAygLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlEhMKCmZpZWxk",
- "bmFtZTEYkQMgASgFEhQKC2ZpZWxkX25hbWUyGJIDIAEoBRIVCgxfZmllbGRf",
- "bmFtZTMYkwMgASgFEhYKDWZpZWxkX19uYW1lNF8YlAMgASgFEhQKC2ZpZWxk",
- "MG5hbWU1GJUDIAEoBRIWCg1maWVsZF8wX25hbWU2GJYDIAEoBRITCgpmaWVs",
- "ZE5hbWU3GJcDIAEoBRITCgpGaWVsZE5hbWU4GJgDIAEoBRIUCgtmaWVsZF9O",
- "YW1lORiZAyABKAUSFQoMRmllbGRfTmFtZTEwGJoDIAEoBRIVCgxGSUVMRF9O",
- "QU1FMTEYmwMgASgFEhUKDEZJRUxEX25hbWUxMhicAyABKAUaSgoNTmVzdGVk",
- "TWVzc2FnZRIJCgFhGAEgASgFEi4KC2NvcmVjdXJzaXZlGAIgASgLMhkuY29u",
- "Zm9ybWFuY2UuVGVzdEFsbFR5cGVzGjQKEk1hcEludDMySW50MzJFbnRyeRIL",
- "CgNrZXkYASABKAUSDQoFdmFsdWUYAiABKAU6AjgBGjQKEk1hcEludDY0SW50",
- "NjRFbnRyeRILCgNrZXkYASABKAMSDQoFdmFsdWUYAiABKAM6AjgBGjYKFE1h",
- "cFVpbnQzMlVpbnQzMkVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEo",
- "DToCOAEaNgoUTWFwVWludDY0VWludDY0RW50cnkSCwoDa2V5GAEgASgEEg0K",
- "BXZhbHVlGAIgASgEOgI4ARo2ChRNYXBTaW50MzJTaW50MzJFbnRyeRILCgNr",
- "ZXkYASABKBESDQoFdmFsdWUYAiABKBE6AjgBGjYKFE1hcFNpbnQ2NFNpbnQ2",
- "NEVudHJ5EgsKA2tleRgBIAEoEhINCgV2YWx1ZRgCIAEoEjoCOAEaOAoWTWFw",
- "Rml4ZWQzMkZpeGVkMzJFbnRyeRILCgNrZXkYASABKAcSDQoFdmFsdWUYAiAB",
- "KAc6AjgBGjgKFk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSCwoDa2V5GAEgASgG",
- "Eg0KBXZhbHVlGAIgASgGOgI4ARo6ChhNYXBTZml4ZWQzMlNmaXhlZDMyRW50",
- "cnkSCwoDa2V5GAEgASgPEg0KBXZhbHVlGAIgASgPOgI4ARo6ChhNYXBTZml4",
- "ZWQ2NFNmaXhlZDY0RW50cnkSCwoDa2V5GAEgASgQEg0KBXZhbHVlGAIgASgQ",
- "OgI4ARo0ChJNYXBJbnQzMkZsb2F0RW50cnkSCwoDa2V5GAEgASgFEg0KBXZh",
- "bHVlGAIgASgCOgI4ARo1ChNNYXBJbnQzMkRvdWJsZUVudHJ5EgsKA2tleRgB",
- "IAEoBRINCgV2YWx1ZRgCIAEoAToCOAEaMgoQTWFwQm9vbEJvb2xFbnRyeRIL",
- "CgNrZXkYASABKAgSDQoFdmFsdWUYAiABKAg6AjgBGjYKFE1hcFN0cmluZ1N0",
- "cmluZ0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEaNQoT",
- "TWFwU3RyaW5nQnl0ZXNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiAB",
- "KAw6AjgBGmYKG01hcFN0cmluZ05lc3RlZE1lc3NhZ2VFbnRyeRILCgNrZXkY",
- "ASABKAkSNgoFdmFsdWUYAiABKAsyJy5jb25mb3JtYW5jZS5UZXN0QWxsVHlw",
- "ZXMuTmVzdGVkTWVzc2FnZToCOAEaWwocTWFwU3RyaW5nRm9yZWlnbk1lc3Nh",
- "Z2VFbnRyeRILCgNrZXkYASABKAkSKgoFdmFsdWUYAiABKAsyGy5jb25mb3Jt",
- "YW5jZS5Gb3JlaWduTWVzc2FnZToCOAEaYAoYTWFwU3RyaW5nTmVzdGVkRW51",
- "bUVudHJ5EgsKA2tleRgBIAEoCRIzCgV2YWx1ZRgCIAEoDjIkLmNvbmZvcm1h",
- "bmNlLlRlc3RBbGxUeXBlcy5OZXN0ZWRFbnVtOgI4ARpVChlNYXBTdHJpbmdG",
- "b3JlaWduRW51bUVudHJ5EgsKA2tleRgBIAEoCRInCgV2YWx1ZRgCIAEoDjIY",
- "LmNvbmZvcm1hbmNlLkZvcmVpZ25FbnVtOgI4ASI5CgpOZXN0ZWRFbnVtEgcK",
- "A0ZPTxAAEgcKA0JBUhABEgcKA0JBWhACEhAKA05FRxD///////////8BQg0K",
- "C29uZW9mX2ZpZWxkIhsKDkZvcmVpZ25NZXNzYWdlEgkKAWMYASABKAUqNQoK",
- "V2lyZUZvcm1hdBIPCgtVTlNQRUNJRklFRBAAEgwKCFBST1RPQlVGEAESCAoE",
- "SlNPThACKkAKC0ZvcmVpZ25FbnVtEg8KC0ZPUkVJR05fRk9PEAASDwoLRk9S",
- "RUlHTl9CQVIQARIPCgtGT1JFSUdOX0JBWhACQiEKH2NvbS5nb29nbGUucHJv",
- "dG9idWYuY29uZm9ybWFuY2ViBnByb3RvMw=="));
+ "aW5nGHEgASgJSAASFQoLb25lb2ZfYnl0ZXMYciABKAxIABIUCgpvbmVvZl9i",
+ "b29sGHMgASgISAASFgoMb25lb2ZfdWludDY0GHQgASgESAASFQoLb25lb2Zf",
+ "ZmxvYXQYdSABKAJIABIWCgxvbmVvZl9kb3VibGUYdiABKAFIABI6CgpvbmVv",
+ "Zl9lbnVtGHcgASgOMiQuY29uZm9ybWFuY2UuVGVzdEFsbFR5cGVzLk5lc3Rl",
+ "ZEVudW1IABI6ChVvcHRpb25hbF9ib29sX3dyYXBwZXIYyQEgASgLMhouZ29v",
+ "Z2xlLnByb3RvYnVmLkJvb2xWYWx1ZRI8ChZvcHRpb25hbF9pbnQzMl93cmFw",
+ "cGVyGMoBIAEoCzIbLmdvb2dsZS5wcm90b2J1Zi5JbnQzMlZhbHVlEjwKFm9w",
+ "dGlvbmFsX2ludDY0X3dyYXBwZXIYywEgASgLMhsuZ29vZ2xlLnByb3RvYnVm",
+ "LkludDY0VmFsdWUSPgoXb3B0aW9uYWxfdWludDMyX3dyYXBwZXIYzAEgASgL",
+ "MhwuZ29vZ2xlLnByb3RvYnVmLlVJbnQzMlZhbHVlEj4KF29wdGlvbmFsX3Vp",
+ "bnQ2NF93cmFwcGVyGM0BIAEoCzIcLmdvb2dsZS5wcm90b2J1Zi5VSW50NjRW",
+ "YWx1ZRI8ChZvcHRpb25hbF9mbG9hdF93cmFwcGVyGM4BIAEoCzIbLmdvb2ds",
+ "ZS5wcm90b2J1Zi5GbG9hdFZhbHVlEj4KF29wdGlvbmFsX2RvdWJsZV93cmFw",
+ "cGVyGM8BIAEoCzIcLmdvb2dsZS5wcm90b2J1Zi5Eb3VibGVWYWx1ZRI+Chdv",
+ "cHRpb25hbF9zdHJpbmdfd3JhcHBlchjQASABKAsyHC5nb29nbGUucHJvdG9i",
+ "dWYuU3RyaW5nVmFsdWUSPAoWb3B0aW9uYWxfYnl0ZXNfd3JhcHBlchjRASAB",
+ "KAsyGy5nb29nbGUucHJvdG9idWYuQnl0ZXNWYWx1ZRI6ChVyZXBlYXRlZF9i",
+ "b29sX3dyYXBwZXIY0wEgAygLMhouZ29vZ2xlLnByb3RvYnVmLkJvb2xWYWx1",
+ "ZRI8ChZyZXBlYXRlZF9pbnQzMl93cmFwcGVyGNQBIAMoCzIbLmdvb2dsZS5w",
+ "cm90b2J1Zi5JbnQzMlZhbHVlEjwKFnJlcGVhdGVkX2ludDY0X3dyYXBwZXIY",
+ "1QEgAygLMhsuZ29vZ2xlLnByb3RvYnVmLkludDY0VmFsdWUSPgoXcmVwZWF0",
+ "ZWRfdWludDMyX3dyYXBwZXIY1gEgAygLMhwuZ29vZ2xlLnByb3RvYnVmLlVJ",
+ "bnQzMlZhbHVlEj4KF3JlcGVhdGVkX3VpbnQ2NF93cmFwcGVyGNcBIAMoCzIc",
+ "Lmdvb2dsZS5wcm90b2J1Zi5VSW50NjRWYWx1ZRI8ChZyZXBlYXRlZF9mbG9h",
+ "dF93cmFwcGVyGNgBIAMoCzIbLmdvb2dsZS5wcm90b2J1Zi5GbG9hdFZhbHVl",
+ "Ej4KF3JlcGVhdGVkX2RvdWJsZV93cmFwcGVyGNkBIAMoCzIcLmdvb2dsZS5w",
+ "cm90b2J1Zi5Eb3VibGVWYWx1ZRI+ChdyZXBlYXRlZF9zdHJpbmdfd3JhcHBl",
+ "chjaASADKAsyHC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUSPAoWcmVw",
+ "ZWF0ZWRfYnl0ZXNfd3JhcHBlchjbASADKAsyGy5nb29nbGUucHJvdG9idWYu",
+ "Qnl0ZXNWYWx1ZRI1ChFvcHRpb25hbF9kdXJhdGlvbhitAiABKAsyGS5nb29n",
+ "bGUucHJvdG9idWYuRHVyYXRpb24SNwoSb3B0aW9uYWxfdGltZXN0YW1wGK4C",
+ "IAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASOAoTb3B0aW9uYWxf",
+ "ZmllbGRfbWFzaxivAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNr",
+ "EjEKD29wdGlvbmFsX3N0cnVjdBiwAiABKAsyFy5nb29nbGUucHJvdG9idWYu",
+ "U3RydWN0EisKDG9wdGlvbmFsX2FueRixAiABKAsyFC5nb29nbGUucHJvdG9i",
+ "dWYuQW55Ei8KDm9wdGlvbmFsX3ZhbHVlGLICIAEoCzIWLmdvb2dsZS5wcm90",
+ "b2J1Zi5WYWx1ZRI1ChFyZXBlYXRlZF9kdXJhdGlvbhi3AiADKAsyGS5nb29n",
+ "bGUucHJvdG9idWYuRHVyYXRpb24SNwoScmVwZWF0ZWRfdGltZXN0YW1wGLgC",
+ "IAMoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASNwoScmVwZWF0ZWRf",
+ "ZmllbGRtYXNrGLkCIAMoCzIaLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE1hc2sS",
+ "MQoPcmVwZWF0ZWRfc3RydWN0GMQCIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5T",
+ "dHJ1Y3QSKwoMcmVwZWF0ZWRfYW55GLsCIAMoCzIULmdvb2dsZS5wcm90b2J1",
+ "Zi5BbnkSLwoOcmVwZWF0ZWRfdmFsdWUYvAIgAygLMhYuZ29vZ2xlLnByb3Rv",
+ "YnVmLlZhbHVlEhMKCmZpZWxkbmFtZTEYkQMgASgFEhQKC2ZpZWxkX25hbWUy",
+ "GJIDIAEoBRIVCgxfZmllbGRfbmFtZTMYkwMgASgFEhYKDWZpZWxkX19uYW1l",
+ "NF8YlAMgASgFEhQKC2ZpZWxkMG5hbWU1GJUDIAEoBRIWCg1maWVsZF8wX25h",
+ "bWU2GJYDIAEoBRITCgpmaWVsZE5hbWU3GJcDIAEoBRITCgpGaWVsZE5hbWU4",
+ "GJgDIAEoBRIUCgtmaWVsZF9OYW1lORiZAyABKAUSFQoMRmllbGRfTmFtZTEw",
+ "GJoDIAEoBRIVCgxGSUVMRF9OQU1FMTEYmwMgASgFEhUKDEZJRUxEX25hbWUx",
+ "MhicAyABKAUSFwoOX19maWVsZF9uYW1lMTMYnQMgASgFEhcKDl9fRmllbGRf",
+ "bmFtZTE0GJ4DIAEoBRIWCg1maWVsZF9fbmFtZTE1GJ8DIAEoBRIWCg1maWVs",
+ "ZF9fTmFtZTE2GKADIAEoBRIXCg5maWVsZF9uYW1lMTdfXxihAyABKAUSFwoO",
+ "RmllbGRfbmFtZTE4X18YogMgASgFGkoKDU5lc3RlZE1lc3NhZ2USCQoBYRgB",
+ "IAEoBRIuCgtjb3JlY3Vyc2l2ZRgCIAEoCzIZLmNvbmZvcm1hbmNlLlRlc3RB",
+ "bGxUeXBlcxo0ChJNYXBJbnQzMkludDMyRW50cnkSCwoDa2V5GAEgASgFEg0K",
+ "BXZhbHVlGAIgASgFOgI4ARo0ChJNYXBJbnQ2NEludDY0RW50cnkSCwoDa2V5",
+ "GAEgASgDEg0KBXZhbHVlGAIgASgDOgI4ARo2ChRNYXBVaW50MzJVaW50MzJF",
+ "bnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBGjYKFE1hcFVp",
+ "bnQ2NFVpbnQ2NEVudHJ5EgsKA2tleRgBIAEoBBINCgV2YWx1ZRgCIAEoBDoC",
+ "OAEaNgoUTWFwU2ludDMyU2ludDMyRW50cnkSCwoDa2V5GAEgASgREg0KBXZh",
+ "bHVlGAIgASgROgI4ARo2ChRNYXBTaW50NjRTaW50NjRFbnRyeRILCgNrZXkY",
+ "ASABKBISDQoFdmFsdWUYAiABKBI6AjgBGjgKFk1hcEZpeGVkMzJGaXhlZDMy",
+ "RW50cnkSCwoDa2V5GAEgASgHEg0KBXZhbHVlGAIgASgHOgI4ARo4ChZNYXBG",
+ "aXhlZDY0Rml4ZWQ2NEVudHJ5EgsKA2tleRgBIAEoBhINCgV2YWx1ZRgCIAEo",
+ "BjoCOAEaOgoYTWFwU2ZpeGVkMzJTZml4ZWQzMkVudHJ5EgsKA2tleRgBIAEo",
+ "DxINCgV2YWx1ZRgCIAEoDzoCOAEaOgoYTWFwU2ZpeGVkNjRTZml4ZWQ2NEVu",
+ "dHJ5EgsKA2tleRgBIAEoEBINCgV2YWx1ZRgCIAEoEDoCOAEaNAoSTWFwSW50",
+ "MzJGbG9hdEVudHJ5EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoAjoCOAEa",
+ "NQoTTWFwSW50MzJEb3VibGVFbnRyeRILCgNrZXkYASABKAUSDQoFdmFsdWUY",
+ "AiABKAE6AjgBGjIKEE1hcEJvb2xCb29sRW50cnkSCwoDa2V5GAEgASgIEg0K",
+ "BXZhbHVlGAIgASgIOgI4ARo2ChRNYXBTdHJpbmdTdHJpbmdFbnRyeRILCgNr",
+ "ZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBGjUKE01hcFN0cmluZ0J5dGVz",
+ "RW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgMOgI4ARpmChtNYXBT",
+ "dHJpbmdOZXN0ZWRNZXNzYWdlRW50cnkSCwoDa2V5GAEgASgJEjYKBXZhbHVl",
+ "GAIgASgLMicuY29uZm9ybWFuY2UuVGVzdEFsbFR5cGVzLk5lc3RlZE1lc3Nh",
+ "Z2U6AjgBGlsKHE1hcFN0cmluZ0ZvcmVpZ25NZXNzYWdlRW50cnkSCwoDa2V5",
+ "GAEgASgJEioKBXZhbHVlGAIgASgLMhsuY29uZm9ybWFuY2UuRm9yZWlnbk1l",
+ "c3NhZ2U6AjgBGmAKGE1hcFN0cmluZ05lc3RlZEVudW1FbnRyeRILCgNrZXkY",
+ "ASABKAkSMwoFdmFsdWUYAiABKA4yJC5jb25mb3JtYW5jZS5UZXN0QWxsVHlw",
+ "ZXMuTmVzdGVkRW51bToCOAEaVQoZTWFwU3RyaW5nRm9yZWlnbkVudW1FbnRy",
+ "eRILCgNrZXkYASABKAkSJwoFdmFsdWUYAiABKA4yGC5jb25mb3JtYW5jZS5G",
+ "b3JlaWduRW51bToCOAEiOQoKTmVzdGVkRW51bRIHCgNGT08QABIHCgNCQVIQ",
+ "ARIHCgNCQVoQAhIQCgNORUcQ////////////AUINCgtvbmVvZl9maWVsZCIb",
+ "Cg5Gb3JlaWduTWVzc2FnZRIJCgFjGAEgASgFKjUKCldpcmVGb3JtYXQSDwoL",
+ "VU5TUEVDSUZJRUQQABIMCghQUk9UT0JVRhABEggKBEpTT04QAipACgtGb3Jl",
+ "aWduRW51bRIPCgtGT1JFSUdOX0ZPTxAAEg8KC0ZPUkVJR05fQkFSEAESDwoL",
+ "Rk9SRUlHTl9CQVoQAkIhCh9jb20uZ29vZ2xlLnByb3RvYnVmLmNvbmZvcm1h",
+ "bmNlYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Conformance.WireFormat), typeof(global::Conformance.ForeignEnum), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceRequest), global::Conformance.ConformanceRequest.Parser, new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat" }, new[]{ "Payload" }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceResponse), global::Conformance.ConformanceResponse.Parser, new[]{ "ParseError", "SerializeError", "RuntimeError", "ProtobufPayload", "JsonPayload", "Skipped" }, new[]{ "Result" }, null, null),
- new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.TestAllTypes), global::Conformance.TestAllTypes.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes", "OptionalBoolWrapper", "OptionalInt32Wrapper", "OptionalInt64Wrapper", "OptionalUint32Wrapper", "OptionalUint64Wrapper", "OptionalFloatWrapper", "OptionalDoubleWrapper", "OptionalStringWrapper", "OptionalBytesWrapper", "RepeatedBoolWrapper", "RepeatedInt32Wrapper", "RepeatedInt64Wrapper", "RepeatedUint32Wrapper", "RepeatedUint64Wrapper", "RepeatedFloatWrapper", "RepeatedDoubleWrapper", "RepeatedStringWrapper", "RepeatedBytesWrapper", "OptionalDuration", "OptionalTimestamp", "OptionalFieldMask", "OptionalStruct", "OptionalAny", "OptionalValue", "RepeatedDuration", "RepeatedTimestamp", "RepeatedFieldmask", "RepeatedStruct", "RepeatedAny", "RepeatedValue", "Fieldname1", "FieldName2", "FieldName3", "FieldName4", "Field0Name5", "Field0Name6", "FieldName7", "FieldName8", "FieldName9", "FieldName10", "FIELDNAME11", "FIELDName12" }, new[]{ "OneofField" }, new[]{ typeof(global::Conformance.TestAllTypes.Types.NestedEnum) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.TestAllTypes.Types.NestedMessage), global::Conformance.TestAllTypes.Types.NestedMessage.Parser, new[]{ "A", "Corecursive" }, null, null, null),
+ new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.TestAllTypes), global::Conformance.TestAllTypes.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes", "OneofBool", "OneofUint64", "OneofFloat", "OneofDouble", "OneofEnum", "OptionalBoolWrapper", "OptionalInt32Wrapper", "OptionalInt64Wrapper", "OptionalUint32Wrapper", "OptionalUint64Wrapper", "OptionalFloatWrapper", "OptionalDoubleWrapper", "OptionalStringWrapper", "OptionalBytesWrapper", "RepeatedBoolWrapper", "RepeatedInt32Wrapper", "RepeatedInt64Wrapper", "RepeatedUint32Wrapper", "RepeatedUint64Wrapper", "RepeatedFloatWrapper", "RepeatedDoubleWrapper", "RepeatedStringWrapper", "RepeatedBytesWrapper", "OptionalDuration", "OptionalTimestamp", "OptionalFieldMask", "OptionalStruct", "OptionalAny", "OptionalValue", "RepeatedDuration", "RepeatedTimestamp", "RepeatedFieldmask", "RepeatedStruct", "RepeatedAny", "RepeatedValue", "Fieldname1", "FieldName2", "FieldName3", "FieldName4", "Field0Name5", "Field0Name6", "FieldName7", "FieldName8", "FieldName9", "FieldName10", "FIELDNAME11", "FIELDName12", "FieldName13", "FieldName14", "FieldName15", "FieldName16", "FieldName17", "FieldName18" }, new[]{ "OneofField" }, new[]{ typeof(global::Conformance.TestAllTypes.Types.NestedEnum) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.TestAllTypes.Types.NestedMessage), global::Conformance.TestAllTypes.Types.NestedMessage.Parser, new[]{ "A", "Corecursive" }, null, null, null),
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ForeignMessage), global::Conformance.ForeignMessage.Parser, new[]{ "C" }, null, null, null)
}));
@@ -890,6 +897,12 @@ namespace Conformance {
fieldName10_ = other.fieldName10_;
fIELDNAME11_ = other.fIELDNAME11_;
fIELDName12_ = other.fIELDName12_;
+ FieldName13_ = other.FieldName13_;
+ FieldName14_ = other.FieldName14_;
+ fieldName15_ = other.fieldName15_;
+ fieldName16_ = other.fieldName16_;
+ fieldName17_ = other.fieldName17_;
+ fieldName18_ = other.fieldName18_;
switch (other.OneofFieldCase) {
case OneofFieldOneofCase.OneofUint32:
OneofUint32 = other.OneofUint32;
@@ -903,6 +916,21 @@ namespace Conformance {
case OneofFieldOneofCase.OneofBytes:
OneofBytes = other.OneofBytes;
break;
+ case OneofFieldOneofCase.OneofBool:
+ OneofBool = other.OneofBool;
+ break;
+ case OneofFieldOneofCase.OneofUint64:
+ OneofUint64 = other.OneofUint64;
+ break;
+ case OneofFieldOneofCase.OneofFloat:
+ OneofFloat = other.OneofFloat;
+ break;
+ case OneofFieldOneofCase.OneofDouble:
+ OneofDouble = other.OneofDouble;
+ break;
+ case OneofFieldOneofCase.OneofEnum:
+ OneofEnum = other.OneofEnum;
+ break;
}
}
@@ -1607,6 +1635,61 @@ namespace Conformance {
}
}
+ /// <summary>Field number for the "oneof_bool" field.</summary>
+ public const int OneofBoolFieldNumber = 115;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public bool OneofBool {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofBool ? (bool) oneofField_ : false; }
+ set {
+ oneofField_ = value;
+ oneofFieldCase_ = OneofFieldOneofCase.OneofBool;
+ }
+ }
+
+ /// <summary>Field number for the "oneof_uint64" field.</summary>
+ public const int OneofUint64FieldNumber = 116;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public ulong OneofUint64 {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofUint64 ? (ulong) oneofField_ : 0UL; }
+ set {
+ oneofField_ = value;
+ oneofFieldCase_ = OneofFieldOneofCase.OneofUint64;
+ }
+ }
+
+ /// <summary>Field number for the "oneof_float" field.</summary>
+ public const int OneofFloatFieldNumber = 117;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public float OneofFloat {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofFloat ? (float) oneofField_ : 0F; }
+ set {
+ oneofField_ = value;
+ oneofFieldCase_ = OneofFieldOneofCase.OneofFloat;
+ }
+ }
+
+ /// <summary>Field number for the "oneof_double" field.</summary>
+ public const int OneofDoubleFieldNumber = 118;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public double OneofDouble {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofDouble ? (double) oneofField_ : 0D; }
+ set {
+ oneofField_ = value;
+ oneofFieldCase_ = OneofFieldOneofCase.OneofDouble;
+ }
+ }
+
+ /// <summary>Field number for the "oneof_enum" field.</summary>
+ public const int OneofEnumFieldNumber = 119;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public global::Conformance.TestAllTypes.Types.NestedEnum OneofEnum {
+ get { return oneofFieldCase_ == OneofFieldOneofCase.OneofEnum ? (global::Conformance.TestAllTypes.Types.NestedEnum) oneofField_ : 0; }
+ set {
+ oneofField_ = value;
+ oneofFieldCase_ = OneofFieldOneofCase.OneofEnum;
+ }
+ }
+
/// <summary>Field number for the "optional_bool_wrapper" field.</summary>
public const int OptionalBoolWrapperFieldNumber = 201;
private static readonly pb::FieldCodec<bool?> _single_optionalBoolWrapper_codec = pb::FieldCodec.ForStructWrapper<bool>(1610);
@@ -1939,6 +2022,7 @@ namespace Conformance {
private int fieldname1_;
/// <summary>
/// Test field-name-to-JSON-name convention.
+ /// (protobuf says names can be any valid C/C++ identifier.)
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Fieldname1 {
@@ -2069,6 +2153,72 @@ namespace Conformance {
}
}
+ /// <summary>Field number for the "__field_name13" field.</summary>
+ public const int FieldName13FieldNumber = 413;
+ private int FieldName13_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int FieldName13 {
+ get { return FieldName13_; }
+ set {
+ FieldName13_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "__Field_name14" field.</summary>
+ public const int FieldName14FieldNumber = 414;
+ private int FieldName14_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int FieldName14 {
+ get { return FieldName14_; }
+ set {
+ FieldName14_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "field__name15" field.</summary>
+ public const int FieldName15FieldNumber = 415;
+ private int fieldName15_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int FieldName15 {
+ get { return fieldName15_; }
+ set {
+ fieldName15_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "field__Name16" field.</summary>
+ public const int FieldName16FieldNumber = 416;
+ private int fieldName16_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int FieldName16 {
+ get { return fieldName16_; }
+ set {
+ fieldName16_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "field_name17__" field.</summary>
+ public const int FieldName17FieldNumber = 417;
+ private int fieldName17_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int FieldName17 {
+ get { return fieldName17_; }
+ set {
+ fieldName17_ = value;
+ }
+ }
+
+ /// <summary>Field number for the "Field_name18__" field.</summary>
+ public const int FieldName18FieldNumber = 418;
+ private int fieldName18_;
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
+ public int FieldName18 {
+ get { return fieldName18_; }
+ set {
+ fieldName18_ = value;
+ }
+ }
+
private object oneofField_;
/// <summary>Enum of possible cases for the "oneof_field" oneof.</summary>
public enum OneofFieldOneofCase {
@@ -2077,6 +2227,11 @@ namespace Conformance {
OneofNestedMessage = 112,
OneofString = 113,
OneofBytes = 114,
+ OneofBool = 115,
+ OneofUint64 = 116,
+ OneofFloat = 117,
+ OneofDouble = 118,
+ OneofEnum = 119,
}
private OneofFieldOneofCase oneofFieldCase_ = OneofFieldOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2169,6 +2324,11 @@ namespace Conformance {
if (!object.Equals(OneofNestedMessage, other.OneofNestedMessage)) return false;
if (OneofString != other.OneofString) return false;
if (OneofBytes != other.OneofBytes) return false;
+ if (OneofBool != other.OneofBool) return false;
+ if (OneofUint64 != other.OneofUint64) return false;
+ if (OneofFloat != other.OneofFloat) return false;
+ if (OneofDouble != other.OneofDouble) return false;
+ if (OneofEnum != other.OneofEnum) return false;
if (OptionalBoolWrapper != other.OptionalBoolWrapper) return false;
if (OptionalInt32Wrapper != other.OptionalInt32Wrapper) return false;
if (OptionalInt64Wrapper != other.OptionalInt64Wrapper) return false;
@@ -2211,6 +2371,12 @@ namespace Conformance {
if (FieldName10 != other.FieldName10) return false;
if (FIELDNAME11 != other.FIELDNAME11) return false;
if (FIELDName12 != other.FIELDName12) return false;
+ if (FieldName13 != other.FieldName13) return false;
+ if (FieldName14 != other.FieldName14) return false;
+ if (FieldName15 != other.FieldName15) return false;
+ if (FieldName16 != other.FieldName16) return false;
+ if (FieldName17 != other.FieldName17) return false;
+ if (FieldName18 != other.FieldName18) return false;
if (OneofFieldCase != other.OneofFieldCase) return false;
return true;
}
@@ -2284,6 +2450,11 @@ namespace Conformance {
if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode();
if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) hash ^= OneofString.GetHashCode();
if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) hash ^= OneofBytes.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofBool) hash ^= OneofBool.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint64) hash ^= OneofUint64.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofFloat) hash ^= OneofFloat.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofDouble) hash ^= OneofDouble.GetHashCode();
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofEnum) hash ^= OneofEnum.GetHashCode();
if (optionalBoolWrapper_ != null) hash ^= OptionalBoolWrapper.GetHashCode();
if (optionalInt32Wrapper_ != null) hash ^= OptionalInt32Wrapper.GetHashCode();
if (optionalInt64Wrapper_ != null) hash ^= OptionalInt64Wrapper.GetHashCode();
@@ -2326,6 +2497,12 @@ namespace Conformance {
if (FieldName10 != 0) hash ^= FieldName10.GetHashCode();
if (FIELDNAME11 != 0) hash ^= FIELDNAME11.GetHashCode();
if (FIELDName12 != 0) hash ^= FIELDName12.GetHashCode();
+ if (FieldName13 != 0) hash ^= FieldName13.GetHashCode();
+ if (FieldName14 != 0) hash ^= FieldName14.GetHashCode();
+ if (FieldName15 != 0) hash ^= FieldName15.GetHashCode();
+ if (FieldName16 != 0) hash ^= FieldName16.GetHashCode();
+ if (FieldName17 != 0) hash ^= FieldName17.GetHashCode();
+ if (FieldName18 != 0) hash ^= FieldName18.GetHashCode();
hash ^= (int) oneofFieldCase_;
return hash;
}
@@ -2481,6 +2658,26 @@ namespace Conformance {
output.WriteRawTag(146, 7);
output.WriteBytes(OneofBytes);
}
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofBool) {
+ output.WriteRawTag(152, 7);
+ output.WriteBool(OneofBool);
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint64) {
+ output.WriteRawTag(160, 7);
+ output.WriteUInt64(OneofUint64);
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofFloat) {
+ output.WriteRawTag(173, 7);
+ output.WriteFloat(OneofFloat);
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofDouble) {
+ output.WriteRawTag(177, 7);
+ output.WriteDouble(OneofDouble);
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofEnum) {
+ output.WriteRawTag(184, 7);
+ output.WriteEnum((int) OneofEnum);
+ }
if (optionalBoolWrapper_ != null) {
_single_optionalBoolWrapper_codec.WriteTagAndValue(output, OptionalBoolWrapper);
}
@@ -2595,6 +2792,30 @@ namespace Conformance {
output.WriteRawTag(224, 25);
output.WriteInt32(FIELDName12);
}
+ if (FieldName13 != 0) {
+ output.WriteRawTag(232, 25);
+ output.WriteInt32(FieldName13);
+ }
+ if (FieldName14 != 0) {
+ output.WriteRawTag(240, 25);
+ output.WriteInt32(FieldName14);
+ }
+ if (FieldName15 != 0) {
+ output.WriteRawTag(248, 25);
+ output.WriteInt32(FieldName15);
+ }
+ if (FieldName16 != 0) {
+ output.WriteRawTag(128, 26);
+ output.WriteInt32(FieldName16);
+ }
+ if (FieldName17 != 0) {
+ output.WriteRawTag(136, 26);
+ output.WriteInt32(FieldName17);
+ }
+ if (FieldName18 != 0) {
+ output.WriteRawTag(144, 26);
+ output.WriteInt32(FieldName18);
+ }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
@@ -2718,6 +2939,21 @@ namespace Conformance {
if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) {
size += 2 + pb::CodedOutputStream.ComputeBytesSize(OneofBytes);
}
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofBool) {
+ size += 2 + 1;
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint64) {
+ size += 2 + pb::CodedOutputStream.ComputeUInt64Size(OneofUint64);
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofFloat) {
+ size += 2 + 4;
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofDouble) {
+ size += 2 + 8;
+ }
+ if (oneofFieldCase_ == OneofFieldOneofCase.OneofEnum) {
+ size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OneofEnum);
+ }
if (optionalBoolWrapper_ != null) {
size += _single_optionalBoolWrapper_codec.CalculateSizeWithTag(OptionalBoolWrapper);
}
@@ -2814,6 +3050,24 @@ namespace Conformance {
if (FIELDName12 != 0) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(FIELDName12);
}
+ if (FieldName13 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(FieldName13);
+ }
+ if (FieldName14 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(FieldName14);
+ }
+ if (FieldName15 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(FieldName15);
+ }
+ if (FieldName16 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(FieldName16);
+ }
+ if (FieldName17 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(FieldName17);
+ }
+ if (FieldName18 != 0) {
+ size += 2 + pb::CodedOutputStream.ComputeInt32Size(FieldName18);
+ }
return size;
}
@@ -3069,6 +3323,24 @@ namespace Conformance {
if (other.FIELDName12 != 0) {
FIELDName12 = other.FIELDName12;
}
+ if (other.FieldName13 != 0) {
+ FieldName13 = other.FieldName13;
+ }
+ if (other.FieldName14 != 0) {
+ FieldName14 = other.FieldName14;
+ }
+ if (other.FieldName15 != 0) {
+ FieldName15 = other.FieldName15;
+ }
+ if (other.FieldName16 != 0) {
+ FieldName16 = other.FieldName16;
+ }
+ if (other.FieldName17 != 0) {
+ FieldName17 = other.FieldName17;
+ }
+ if (other.FieldName18 != 0) {
+ FieldName18 = other.FieldName18;
+ }
switch (other.OneofFieldCase) {
case OneofFieldOneofCase.OneofUint32:
OneofUint32 = other.OneofUint32;
@@ -3082,6 +3354,21 @@ namespace Conformance {
case OneofFieldOneofCase.OneofBytes:
OneofBytes = other.OneofBytes;
break;
+ case OneofFieldOneofCase.OneofBool:
+ OneofBool = other.OneofBool;
+ break;
+ case OneofFieldOneofCase.OneofUint64:
+ OneofUint64 = other.OneofUint64;
+ break;
+ case OneofFieldOneofCase.OneofFloat:
+ OneofFloat = other.OneofFloat;
+ break;
+ case OneofFieldOneofCase.OneofDouble:
+ OneofDouble = other.OneofDouble;
+ break;
+ case OneofFieldOneofCase.OneofEnum:
+ OneofEnum = other.OneofEnum;
+ break;
}
}
@@ -3387,6 +3674,27 @@ namespace Conformance {
OneofBytes = input.ReadBytes();
break;
}
+ case 920: {
+ OneofBool = input.ReadBool();
+ break;
+ }
+ case 928: {
+ OneofUint64 = input.ReadUInt64();
+ break;
+ }
+ case 941: {
+ OneofFloat = input.ReadFloat();
+ break;
+ }
+ case 945: {
+ OneofDouble = input.ReadDouble();
+ break;
+ }
+ case 952: {
+ oneofField_ = input.ReadEnum();
+ oneofFieldCase_ = OneofFieldOneofCase.OneofEnum;
+ break;
+ }
case 1610: {
bool? value = _single_optionalBoolWrapper_codec.Read(input);
if (optionalBoolWrapper_ == null || value != false) {
@@ -3600,6 +3908,30 @@ namespace Conformance {
FIELDName12 = input.ReadInt32();
break;
}
+ case 3304: {
+ FieldName13 = input.ReadInt32();
+ break;
+ }
+ case 3312: {
+ FieldName14 = input.ReadInt32();
+ break;
+ }
+ case 3320: {
+ FieldName15 = input.ReadInt32();
+ break;
+ }
+ case 3328: {
+ FieldName16 = input.ReadInt32();
+ break;
+ }
+ case 3336: {
+ FieldName17 = input.ReadInt32();
+ break;
+ }
+ case 3344: {
+ FieldName18 = input.ReadInt32();
+ break;
+ }
}
}
}
diff --git a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
index 261ac6a7..302f8143 100644
--- a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
+++ b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
@@ -229,16 +229,16 @@ namespace Google.Protobuf
[Test]
[TestCase("foo_bar", "fooBar")]
[TestCase("bananaBanana", "bananaBanana")]
- [TestCase("BANANABanana", "bananaBanana")]
+ [TestCase("BANANABanana", "BANANABanana")]
[TestCase("simple", "simple")]
- [TestCase("ACTION_AND_ADVENTURE", "actionAndAdventure")]
+ [TestCase("ACTION_AND_ADVENTURE", "ACTIONANDADVENTURE")]
[TestCase("action_and_adventure", "actionAndAdventure")]
[TestCase("kFoo", "kFoo")]
- [TestCase("HTTPServer", "httpServer")]
- [TestCase("CLIENT", "client")]
- public void ToCamelCase(string original, string expected)
+ [TestCase("HTTPServer", "HTTPServer")]
+ [TestCase("CLIENT", "CLIENT")]
+ public void ToJsonName(string original, string expected)
{
- Assert.AreEqual(expected, JsonFormatter.ToCamelCase(original));
+ Assert.AreEqual(expected, JsonFormatter.ToJsonName(original));
}
[Test]
diff --git a/csharp/src/Google.Protobuf.Test/project.json b/csharp/src/Google.Protobuf.Test/project.json
index 87b732c9..3a73bf7a 100644
--- a/csharp/src/Google.Protobuf.Test/project.json
+++ b/csharp/src/Google.Protobuf.Test/project.json
@@ -21,7 +21,7 @@
"dependencies": {
"Google.Protobuf": { "target": "project" },
"NUnit": "3.4.0",
- "dotnet-test-nunit": "3.4.0-alpha-2",
+ "dotnet-test-nunit": "3.4.0-alpha-2"
},
"testRunner": "nunit",
diff --git a/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs b/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs
index eeb0f13a..0fbc5306 100644
--- a/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs
+++ b/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs
@@ -61,7 +61,7 @@ namespace Google.Protobuf
{
return new InvalidProtocolBufferException(
"While parsing a protocol message, the input ended unexpectedly " +
- "in the middle of a field. This could mean either than the " +
+ "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.");
}
diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs
index d8a814d9..bb1a361e 100644
--- a/csharp/src/Google.Protobuf/JsonFormatter.cs
+++ b/csharp/src/Google.Protobuf/JsonFormatter.cs
@@ -248,87 +248,25 @@ namespace Google.Protobuf
return !first;
}
- /// <summary>
- /// Camel-case converter with added strictness for field mask formatting.
- /// </summary>
- /// <exception cref="InvalidOperationException">The field mask is invalid for JSON representation</exception>
- private static string ToCamelCaseForFieldMask(string input)
+ // Converted from java/core/src/main/java/com/google/protobuf/Descriptors.java
+ internal static string ToJsonName(string name)
{
- for (int i = 0; i < input.Length; i++)
+ StringBuilder result = new StringBuilder(name.Length);
+ bool isNextUpperCase = false;
+ foreach (char ch in name)
{
- char c = input[i];
- if (c >= 'A' && c <= 'Z')
+ if (ch == '_')
{
- throw new InvalidOperationException($"Invalid field mask to be converted to JSON: {input}");
+ isNextUpperCase = true;
}
- if (c == '_' && i < input.Length - 1)
- {
- char next = input[i + 1];
- if (next < 'a' || next > 'z')
- {
- throw new InvalidOperationException($"Invalid field mask to be converted to JSON: {input}");
- }
- }
- }
- return ToCamelCase(input);
- }
-
- // Converted from src/google/protobuf/util/internal/utility.cc ToCamelCase
- internal static string ToCamelCase(string input)
- {
- bool capitalizeNext = false;
- bool wasCap = true;
- bool isCap = false;
- bool firstWord = true;
- StringBuilder result = new StringBuilder(input.Length);
-
- for (int i = 0; i < input.Length; i++, wasCap = isCap)
- {
- isCap = char.IsUpper(input[i]);
- if (input[i] == '_')
+ else if (isNextUpperCase)
{
- capitalizeNext = true;
- if (result.Length != 0)
- {
- firstWord = false;
- }
- continue;
- }
- else if (firstWord)
- {
- // Consider when the current character B is capitalized,
- // first word ends when:
- // 1) following a lowercase: "...aB..."
- // 2) followed by a lowercase: "...ABc..."
- if (result.Length != 0 && isCap &&
- (!wasCap || (i + 1 < input.Length && char.IsLower(input[i + 1]))))
- {
- firstWord = false;
- result.Append(input[i]);
- }
- else
- {
- result.Append(char.ToLowerInvariant(input[i]));
- continue;
- }
- }
- else if (capitalizeNext)
- {
- capitalizeNext = false;
- if (char.IsLower(input[i]))
- {
- result.Append(char.ToUpperInvariant(input[i]));
- continue;
- }
- else
- {
- result.Append(input[i]);
- continue;
- }
+ result.Append(char.ToUpperInvariant(ch));
+ isNextUpperCase = false;
}
else
{
- result.Append(char.ToLowerInvariant(input[i]));
+ result.Append(ch);
}
}
return result.ToString();
diff --git a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
index 83e7928a..19155469 100644
--- a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
@@ -80,66 +80,66 @@ namespace Google.Protobuf.Reflection {
"ASgJEhMKC291dHB1dF90eXBlGAMgASgJEi8KB29wdGlvbnMYBCABKAsyHi5n",
"b29nbGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucxIfChBjbGllbnRfc3RyZWFt",
"aW5nGAUgASgIOgVmYWxzZRIfChBzZXJ2ZXJfc3RyZWFtaW5nGAYgASgIOgVm",
- "YWxzZSKHBQoLRmlsZU9wdGlvbnMSFAoMamF2YV9wYWNrYWdlGAEgASgJEhwK",
+ "YWxzZSKEBQoLRmlsZU9wdGlvbnMSFAoMamF2YV9wYWNrYWdlGAEgASgJEhwK",
"FGphdmFfb3V0ZXJfY2xhc3NuYW1lGAggASgJEiIKE2phdmFfbXVsdGlwbGVf",
- "ZmlsZXMYCiABKAg6BWZhbHNlEiwKHWphdmFfZ2VuZXJhdGVfZXF1YWxzX2Fu",
- "ZF9oYXNoGBQgASgIOgVmYWxzZRIlChZqYXZhX3N0cmluZ19jaGVja191dGY4",
- "GBsgASgIOgVmYWxzZRJGCgxvcHRpbWl6ZV9mb3IYCSABKA4yKS5nb29nbGUu",
- "cHJvdG9idWYuRmlsZU9wdGlvbnMuT3B0aW1pemVNb2RlOgVTUEVFRBISCgpn",
- "b19wYWNrYWdlGAsgASgJEiIKE2NjX2dlbmVyaWNfc2VydmljZXMYECABKAg6",
- "BWZhbHNlEiQKFWphdmFfZ2VuZXJpY19zZXJ2aWNlcxgRIAEoCDoFZmFsc2US",
- "IgoTcHlfZ2VuZXJpY19zZXJ2aWNlcxgSIAEoCDoFZmFsc2USGQoKZGVwcmVj",
- "YXRlZBgXIAEoCDoFZmFsc2USHwoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoF",
- "ZmFsc2USGQoRb2JqY19jbGFzc19wcmVmaXgYJCABKAkSGAoQY3NoYXJwX25h",
- "bWVzcGFjZRglIAEoCRJDChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsy",
- "JC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbiI6CgxPcHRp",
- "bWl6ZU1vZGUSCQoFU1BFRUQQARINCglDT0RFX1NJWkUQAhIQCgxMSVRFX1JV",
- "TlRJTUUQAyoJCOgHEICAgIACSgQIJhAnIuYBCg5NZXNzYWdlT3B0aW9ucxIm",
- "ChdtZXNzYWdlX3NldF93aXJlX2Zvcm1hdBgBIAEoCDoFZmFsc2USLgofbm9f",
- "c3RhbmRhcmRfZGVzY3JpcHRvcl9hY2Nlc3NvchgCIAEoCDoFZmFsc2USGQoK",
- "ZGVwcmVjYXRlZBgDIAEoCDoFZmFsc2USEQoJbWFwX2VudHJ5GAcgASgIEkMK",
- "FHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1",
- "Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIimAMKDEZpZWxkT3B0",
- "aW9ucxI6CgVjdHlwZRgBIAEoDjIjLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9w",
- "dGlvbnMuQ1R5cGU6BlNUUklORxIOCgZwYWNrZWQYAiABKAgSPwoGanN0eXBl",
- "GAYgASgOMiQuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5KU1R5cGU6",
- "CUpTX05PUk1BTBITCgRsYXp5GAUgASgIOgVmYWxzZRIZCgpkZXByZWNhdGVk",
- "GAMgASgIOgVmYWxzZRITCgR3ZWFrGAogASgIOgVmYWxzZRJDChR1bmludGVy",
- "cHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRl",
- "cnByZXRlZE9wdGlvbiIvCgVDVHlwZRIKCgZTVFJJTkcQABIICgRDT1JEEAES",
- "EAoMU1RSSU5HX1BJRUNFEAIiNQoGSlNUeXBlEg0KCUpTX05PUk1BTBAAEg0K",
- "CUpTX1NUUklORxABEg0KCUpTX05VTUJFUhACKgkI6AcQgICAgAIiXgoMT25l",
- "b2ZPcHRpb25zEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdv",
- "b2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi",
- "jQEKC0VudW1PcHRpb25zEhMKC2FsbG93X2FsaWFzGAIgASgIEhkKCmRlcHJl",
- "Y2F0ZWQYAyABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcH",
+ "ZmlsZXMYCiABKAg6BWZhbHNlEikKHWphdmFfZ2VuZXJhdGVfZXF1YWxzX2Fu",
+ "ZF9oYXNoGBQgASgIQgIYARIlChZqYXZhX3N0cmluZ19jaGVja191dGY4GBsg",
+ "ASgIOgVmYWxzZRJGCgxvcHRpbWl6ZV9mb3IYCSABKA4yKS5nb29nbGUucHJv",
+ "dG9idWYuRmlsZU9wdGlvbnMuT3B0aW1pemVNb2RlOgVTUEVFRBISCgpnb19w",
+ "YWNrYWdlGAsgASgJEiIKE2NjX2dlbmVyaWNfc2VydmljZXMYECABKAg6BWZh",
+ "bHNlEiQKFWphdmFfZ2VuZXJpY19zZXJ2aWNlcxgRIAEoCDoFZmFsc2USIgoT",
+ "cHlfZ2VuZXJpY19zZXJ2aWNlcxgSIAEoCDoFZmFsc2USGQoKZGVwcmVjYXRl",
+ "ZBgXIAEoCDoFZmFsc2USHwoQY2NfZW5hYmxlX2FyZW5hcxgfIAEoCDoFZmFs",
+ "c2USGQoRb2JqY19jbGFzc19wcmVmaXgYJCABKAkSGAoQY3NoYXJwX25hbWVz",
+ "cGFjZRglIAEoCRJDChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5n",
+ "b29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbiI6CgxPcHRpbWl6",
+ "ZU1vZGUSCQoFU1BFRUQQARINCglDT0RFX1NJWkUQAhIQCgxMSVRFX1JVTlRJ",
+ "TUUQAyoJCOgHEICAgIACSgQIJhAnIuwBCg5NZXNzYWdlT3B0aW9ucxImChdt",
+ "ZXNzYWdlX3NldF93aXJlX2Zvcm1hdBgBIAEoCDoFZmFsc2USLgofbm9fc3Rh",
+ "bmRhcmRfZGVzY3JpcHRvcl9hY2Nlc3NvchgCIAEoCDoFZmFsc2USGQoKZGVw",
+ "cmVjYXRlZBgDIAEoCDoFZmFsc2USEQoJbWFwX2VudHJ5GAcgASgIEkMKFHVu",
+ "aW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5V",
+ "bmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAJKBAgIEAkingMKDEZpZWxk",
+ "T3B0aW9ucxI6CgVjdHlwZRgBIAEoDjIjLmdvb2dsZS5wcm90b2J1Zi5GaWVs",
+ "ZE9wdGlvbnMuQ1R5cGU6BlNUUklORxIOCgZwYWNrZWQYAiABKAgSPwoGanN0",
+ "eXBlGAYgASgOMiQuZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucy5KU1R5",
+ "cGU6CUpTX05PUk1BTBITCgRsYXp5GAUgASgIOgVmYWxzZRIZCgpkZXByZWNh",
+ "dGVkGAMgASgIOgVmYWxzZRITCgR3ZWFrGAogASgIOgVmYWxzZRJDChR1bmlu",
+ "dGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5p",
+ "bnRlcnByZXRlZE9wdGlvbiIvCgVDVHlwZRIKCgZTVFJJTkcQABIICgRDT1JE",
+ "EAESEAoMU1RSSU5HX1BJRUNFEAIiNQoGSlNUeXBlEg0KCUpTX05PUk1BTBAA",
+ "Eg0KCUpTX1NUUklORxABEg0KCUpTX05VTUJFUhACKgkI6AcQgICAgAJKBAgE",
+ "EAUiXgoMT25lb2ZPcHRpb25zEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcH",
"IAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI",
- "6AcQgICAgAIifQoQRW51bVZhbHVlT3B0aW9ucxIZCgpkZXByZWNhdGVkGAEg",
- "ASgIOgVmYWxzZRJDChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5n",
- "b29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIAC",
- "InsKDlNlcnZpY2VPcHRpb25zEhkKCmRlcHJlY2F0ZWQYISABKAg6BWZhbHNl",
- "EkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90",
- "b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIiegoNTWV0aG9k",
- "T3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJDChR1bmludGVy",
- "cHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRl",
- "cnByZXRlZE9wdGlvbioJCOgHEICAgIACIp4CChNVbmludGVycHJldGVkT3B0",
- "aW9uEjsKBG5hbWUYAiADKAsyLS5nb29nbGUucHJvdG9idWYuVW5pbnRlcnBy",
- "ZXRlZE9wdGlvbi5OYW1lUGFydBIYChBpZGVudGlmaWVyX3ZhbHVlGAMgASgJ",
- "EhoKEnBvc2l0aXZlX2ludF92YWx1ZRgEIAEoBBIaChJuZWdhdGl2ZV9pbnRf",
- "dmFsdWUYBSABKAMSFAoMZG91YmxlX3ZhbHVlGAYgASgBEhQKDHN0cmluZ192",
- "YWx1ZRgHIAEoDBIXCg9hZ2dyZWdhdGVfdmFsdWUYCCABKAkaMwoITmFtZVBh",
- "cnQSEQoJbmFtZV9wYXJ0GAEgAigJEhQKDGlzX2V4dGVuc2lvbhgCIAIoCCLV",
- "AQoOU291cmNlQ29kZUluZm8SOgoIbG9jYXRpb24YASADKAsyKC5nb29nbGUu",
- "cHJvdG9idWYuU291cmNlQ29kZUluZm8uTG9jYXRpb24ahgEKCExvY2F0aW9u",
- "EhAKBHBhdGgYASADKAVCAhABEhAKBHNwYW4YAiADKAVCAhABEhgKEGxlYWRp",
- "bmdfY29tbWVudHMYAyABKAkSGQoRdHJhaWxpbmdfY29tbWVudHMYBCABKAkS",
- "IQoZbGVhZGluZ19kZXRhY2hlZF9jb21tZW50cxgGIAMoCSKnAQoRR2VuZXJh",
- "dGVkQ29kZUluZm8SQQoKYW5ub3RhdGlvbhgBIAMoCzItLmdvb2dsZS5wcm90",
- "b2J1Zi5HZW5lcmF0ZWRDb2RlSW5mby5Bbm5vdGF0aW9uGk8KCkFubm90YXRp",
- "b24SEAoEcGF0aBgBIAMoBUICEAESEwoLc291cmNlX2ZpbGUYAiABKAkSDQoF",
- "YmVnaW4YAyABKAUSCwoDZW5kGAQgASgFQlsKE2NvbS5nb29nbGUucHJvdG9i",
- "dWZCEERlc2NyaXB0b3JQcm90b3NIAVoKZGVzY3JpcHRvcqABAaICA0dQQqoC",
- "Gkdvb2dsZS5Qcm90b2J1Zi5SZWZsZWN0aW9u"));
+ "6AcQgICAgAIijQEKC0VudW1PcHRpb25zEhMKC2FsbG93X2FsaWFzGAIgASgI",
+ "EhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRf",
+ "b3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVk",
+ "T3B0aW9uKgkI6AcQgICAgAIifQoQRW51bVZhbHVlT3B0aW9ucxIZCgpkZXBy",
+ "ZWNhdGVkGAEgASgIOgVmYWxzZRJDChR1bmludGVycHJldGVkX29wdGlvbhjn",
+ "ByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbioJ",
+ "COgHEICAgIACInsKDlNlcnZpY2VPcHRpb25zEhkKCmRlcHJlY2F0ZWQYISAB",
+ "KAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdv",
+ "b2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi",
+ "egoNTWV0aG9kT3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgIOgVmYWxzZRJD",
+ "ChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9i",
+ "dWYuVW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACIp4CChNVbmludGVy",
+ "cHJldGVkT3B0aW9uEjsKBG5hbWUYAiADKAsyLS5nb29nbGUucHJvdG9idWYu",
+ "VW5pbnRlcnByZXRlZE9wdGlvbi5OYW1lUGFydBIYChBpZGVudGlmaWVyX3Zh",
+ "bHVlGAMgASgJEhoKEnBvc2l0aXZlX2ludF92YWx1ZRgEIAEoBBIaChJuZWdh",
+ "dGl2ZV9pbnRfdmFsdWUYBSABKAMSFAoMZG91YmxlX3ZhbHVlGAYgASgBEhQK",
+ "DHN0cmluZ192YWx1ZRgHIAEoDBIXCg9hZ2dyZWdhdGVfdmFsdWUYCCABKAka",
+ "MwoITmFtZVBhcnQSEQoJbmFtZV9wYXJ0GAEgAigJEhQKDGlzX2V4dGVuc2lv",
+ "bhgCIAIoCCLVAQoOU291cmNlQ29kZUluZm8SOgoIbG9jYXRpb24YASADKAsy",
+ "KC5nb29nbGUucHJvdG9idWYuU291cmNlQ29kZUluZm8uTG9jYXRpb24ahgEK",
+ "CExvY2F0aW9uEhAKBHBhdGgYASADKAVCAhABEhAKBHNwYW4YAiADKAVCAhAB",
+ "EhgKEGxlYWRpbmdfY29tbWVudHMYAyABKAkSGQoRdHJhaWxpbmdfY29tbWVu",
+ "dHMYBCABKAkSIQoZbGVhZGluZ19kZXRhY2hlZF9jb21tZW50cxgGIAMoCSKn",
+ "AQoRR2VuZXJhdGVkQ29kZUluZm8SQQoKYW5ub3RhdGlvbhgBIAMoCzItLmdv",
+ "b2dsZS5wcm90b2J1Zi5HZW5lcmF0ZWRDb2RlSW5mby5Bbm5vdGF0aW9uGk8K",
+ "CkFubm90YXRpb24SEAoEcGF0aBgBIAMoBUICEAESEwoLc291cmNlX2ZpbGUY",
+ "AiABKAkSDQoFYmVnaW4YAyABKAUSCwoDZW5kGAQgASgFQlgKE2NvbS5nb29n",
+ "bGUucHJvdG9idWZCEERlc2NyaXB0b3JQcm90b3NIAVoKZGVzY3JpcHRvcqIC",
+ "A0dQQqoCGkdvb2dsZS5Qcm90b2J1Zi5SZWZsZWN0aW9u"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
@@ -2865,19 +2865,9 @@ namespace Google.Protobuf.Reflection {
public const int JavaGenerateEqualsAndHashFieldNumber = 20;
private bool javaGenerateEqualsAndHash_;
/// <summary>
- /// If set true, then the Java code generator will generate equals() and
- /// hashCode() methods for all messages defined in the .proto file.
- /// This increases generated code size, potentially substantially for large
- /// protos, which may harm a memory-constrained application.
- /// - In the full runtime this is a speed optimization, as the
- /// AbstractMessage base class includes reflection-based implementations of
- /// these methods.
- /// - In the lite runtime, setting this option changes the semantics of
- /// equals() and hashCode() to more closely match those of the full runtime;
- /// the generated methods compute their results based on field values rather
- /// than object identity. (Implementations should not assume that hashcodes
- /// will be consistent across runtimes or versions of the protocol compiler.)
+ /// This option does nothing.
/// </summary>
+ [global::System.ObsoleteAttribute]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool JavaGenerateEqualsAndHash {
get { return javaGenerateEqualsAndHash_; }
@@ -3764,7 +3754,7 @@ namespace Google.Protobuf.Reflection {
/// to require exclusive access.
///
/// Note that implementations may choose not to check required fields within
- /// a lazy sub-message. That is, calling IsInitialized() on the outher message
+ /// a lazy sub-message. That is, calling IsInitialized() on the outer message
/// may return true even if the inner message has missing required fields.
/// This is necessary because otherwise the inner message would have to be
/// parsed in order to perform the check, defeating the purpose of lazy
diff --git a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
index 6c6f6ee0..ed15d0e1 100644
--- a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs
@@ -97,7 +97,7 @@ namespace Google.Protobuf.Reflection
// We could trust the generated code and check whether the type of the property is
// a MapField, but that feels a tad nasty.
this.propertyName = propertyName;
- JsonName = Proto.JsonName == "" ? JsonFormatter.ToCamelCase(Proto.Name) : Proto.JsonName;
+ JsonName = Proto.JsonName == "" ? JsonFormatter.ToJsonName(Proto.Name) : Proto.JsonName;
}
diff --git a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
index ab7cd922..94efea9e 100644
--- a/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
+++ b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs
@@ -251,17 +251,6 @@ namespace Google.Protobuf.Reflection
"Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto.");
}
- for (int i = 0; i < proto.Dependency.Count; i++)
- {
- if (dependencies[i].Name != proto.Dependency[i])
- {
- throw new DescriptorValidationException(
- result,
- "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
- "those listed in the FileDescriptorProto. Expected: " +
- proto.Dependency[i] + " but was: " + dependencies[i].Name);
- }
- }
result.CrossLink();
return result;
@@ -341,4 +330,4 @@ namespace Google.Protobuf.Reflection
/// </value>
public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
}
-} \ No newline at end of file
+}
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
index 6f91507b..e36fd5eb 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs
@@ -23,10 +23,10 @@ namespace Google.Protobuf.WellKnownTypes {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYi",
- "JgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnIKE2Nv",
+ "JgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQm8KE2Nv",
"bS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaJWdpdGh1Yi5jb20vZ29s",
- "YW5nL3Byb3RvYnVmL3B0eXBlcy9hbnmgAQGiAgNHUEKqAh5Hb29nbGUuUHJv",
- "dG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw=="));
+ "YW5nL3Byb3RvYnVmL3B0eXBlcy9hbnmiAgNHUEKqAh5Hb29nbGUuUHJvdG9i",
+ "dWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
index a9fc51d2..234095e9 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs
@@ -35,9 +35,9 @@ namespace Google.Protobuf.WellKnownTypes {
"ChFyZXNwb25zZV90eXBlX3VybBgEIAEoCRIaChJyZXNwb25zZV9zdHJlYW1p",
"bmcYBSABKAgSKAoHb3B0aW9ucxgGIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5P",
"cHRpb24SJwoGc3ludGF4GAcgASgOMhcuZ29vZ2xlLnByb3RvYnVmLlN5bnRh",
- "eCIjCgVNaXhpbhIMCgRuYW1lGAEgASgJEgwKBHJvb3QYAiABKAlCSwoTY29t",
- "Lmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJvdG9QAaABAaICA0dQQqoCHkdvb2ds",
- "ZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z"));
+ "eCIjCgVNaXhpbhIMCgRuYW1lGAEgASgJEgwKBHJvb3QYAiABKAlCSAoTY29t",
+ "Lmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJvdG9QAaICA0dQQqoCHkdvb2dsZS5Q",
+ "cm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.SourceContextReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
index 5d52330c..66ac7152 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs
@@ -25,7 +25,7 @@ namespace Google.Protobuf.WellKnownTypes {
"Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90",
"b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIg",
"ASgFQnwKE2NvbS5nb29nbGUucHJvdG9idWZCDUR1cmF0aW9uUHJvdG9QAVoq",
- "Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHR5cGVzL2R1cmF0aW9uoAEB",
+ "Z2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHR5cGVzL2R1cmF0aW9u+AEB",
"ogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90",
"bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
@@ -79,6 +79,12 @@ namespace Google.Protobuf.WellKnownTypes {
/// end.seconds += 1;
/// end.nanos -= 1000000000;
/// }
+ ///
+ /// Example 3: Compute Duration from datetime.timedelta in Python.
+ ///
+ /// td = datetime.timedelta(days=3, minutes=10)
+ /// duration = Duration()
+ /// duration.FromTimedelta(td)
/// </summary>
public sealed partial class Duration : pb::IMessage<Duration> {
private static readonly pb::MessageParser<Duration> _parser = new pb::MessageParser<Duration>(() => new Duration());
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
index 1d3376ee..0e64133e 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
@@ -23,10 +23,10 @@ namespace Google.Protobuf.WellKnownTypes {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8SD2dvb2dsZS5wcm90b2J1",
- "ZiIHCgVFbXB0eUJ5ChNjb20uZ29vZ2xlLnByb3RvYnVmQgpFbXB0eVByb3Rv",
- "UAFaJ2dpdGh1Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy9lbXB0eaAB",
- "AfgBAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG",
- "cHJvdG8z"));
+ "ZiIHCgVFbXB0eUJ2ChNjb20uZ29vZ2xlLnByb3RvYnVmQgpFbXB0eVByb3Rv",
+ "UAFaJ2dpdGh1Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy9lbXB0efgB",
+ "AaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJv",
+ "dG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
index 3b146822..c73d6bd8 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs
@@ -23,9 +23,9 @@ namespace Google.Protobuf.WellKnownTypes {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy",
- "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUJRChNjb20uZ29v",
- "Z2xlLnByb3RvYnVmQg5GaWVsZE1hc2tQcm90b1ABoAEBogIDR1BCqgIeR29v",
- "Z2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM="));
+ "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUJOChNjb20uZ29v",
+ "Z2xlLnByb3RvYnVmQg5GaWVsZE1hc2tQcm90b1ABogIDR1BCqgIeR29vZ2xl",
+ "LlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
@@ -79,7 +79,7 @@ namespace Google.Protobuf.WellKnownTypes {
/// }
///
/// A repeated field is not allowed except at the last position of a
- /// field mask.
+ /// paths string.
///
/// If a FieldMask object is not present in a get operation, the
/// operation applies to all fields (as if a FieldMask of all fields
@@ -106,8 +106,8 @@ namespace Google.Protobuf.WellKnownTypes {
///
/// If a repeated field is specified for an update operation, the existing
/// repeated values in the target resource will be overwritten by the new values.
- /// Note that a repeated field is only allowed in the last position of a field
- /// mask.
+ /// Note that a repeated field is only allowed in the last position of a `paths`
+ /// string.
///
/// If a sub-message is specified in the last position of the field mask for an
/// update operation, then the existing sub-message in the target resource is
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
index f9cdb8af..0685c21a 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMaskPartial.cs
@@ -52,7 +52,7 @@ namespace Google.Protobuf.WellKnownTypes
/// </remarks>
/// <param name="paths">Paths in the field mask</param>
/// <param name="diagnosticOnly">Determines the handling of non-normalized values</param>
- /// <exception cref="InvalidOperationException">The represented duration is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception>
+ /// <exception cref="InvalidOperationException">The represented field mask is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception>
internal static string ToJson(IList<string> paths, bool diagnosticOnly)
{
var firstInvalid = paths.FirstOrDefault(p => !ValidatePath(p));
@@ -60,10 +60,10 @@ namespace Google.Protobuf.WellKnownTypes
{
var writer = new StringWriter();
#if DOTNET35
- var query = paths.Select(JsonFormatter.ToCamelCase);
+ var query = paths.Select(JsonFormatter.ToJsonName);
JsonFormatter.WriteString(writer, string.Join(",", query.ToArray()));
#else
- JsonFormatter.WriteString(writer, string.Join(",", paths.Select(JsonFormatter.ToCamelCase)));
+ JsonFormatter.WriteString(writer, string.Join(",", paths.Select(JsonFormatter.ToJsonName)));
#endif
return writer.ToString();
}
@@ -85,9 +85,9 @@ namespace Google.Protobuf.WellKnownTypes
}
/// <summary>
- /// Camel-case converter with added strictness for field mask formatting.
+ /// Checks whether the given path is valid for a field mask.
/// </summary>
- /// <exception cref="InvalidOperationException">The field mask is invalid for JSON representation</exception>
+ /// <returns>true if the path is valid; false otherwise</returns>
private static bool ValidatePath(string input)
{
for (int i = 0; i < input.Length; i++)
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs b/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs
index c9992d2d..c3400327 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs
@@ -24,9 +24,9 @@ namespace Google.Protobuf.WellKnownTypes {
string.Concat(
"CiRnb29nbGUvcHJvdG9idWYvc291cmNlX2NvbnRleHQucHJvdG8SD2dvb2ds",
"ZS5wcm90b2J1ZiIiCg1Tb3VyY2VDb250ZXh0EhEKCWZpbGVfbmFtZRgBIAEo",
- "CUJVChNjb20uZ29vZ2xlLnByb3RvYnVmQhJTb3VyY2VDb250ZXh0UHJvdG9Q",
- "AaABAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG",
- "cHJvdG8z"));
+ "CUJSChNjb20uZ29vZ2xlLnByb3RvYnVmQhJTb3VyY2VDb250ZXh0UHJvdG9Q",
+ "AaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJv",
+ "dG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
index b3d62fbf..d4556051 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs
@@ -35,7 +35,7 @@ namespace Google.Protobuf.WellKnownTypes {
"Lmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9W",
"QUxVRRAAQoEBChNjb20uZ29vZ2xlLnByb3RvYnVmQgtTdHJ1Y3RQcm90b1AB",
"WjFnaXRodWIuY29tL2dvbGFuZy9wcm90b2J1Zi9wdHlwZXMvc3RydWN0O3N0",
- "cnVjdHBioAEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5",
+ "cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5",
"cGVzYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
index 5157e6d5..6c9a517f 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs
@@ -24,10 +24,10 @@ namespace Google.Protobuf.WellKnownTypes {
string.Concat(
"Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv",
"dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY",
- "AiABKAVCgQEKE2NvbS5nb29nbGUucHJvdG9idWZCDlRpbWVzdGFtcFByb3Rv",
- "UAFaK2dpdGh1Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy90aW1lc3Rh",
- "bXCgAQH4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlw",
- "ZXNiBnByb3RvMw=="));
+ "AiABKAVCfgoTY29tLmdvb2dsZS5wcm90b2J1ZkIOVGltZXN0YW1wUHJvdG9Q",
+ "AVorZ2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHR5cGVzL3RpbWVzdGFt",
+ "cPgBAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG",
+ "cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
@@ -87,10 +87,8 @@ namespace Google.Protobuf.WellKnownTypes {
///
/// Example 5: Compute Timestamp from current time in Python.
///
- /// now = time.time()
- /// seconds = int(now)
- /// nanos = int((now - seconds) * 10**9)
- /// timestamp = Timestamp(seconds=seconds, nanos=nanos)
+ /// timestamp = Timestamp()
+ /// timestamp.GetCurrentTime()
/// </summary>
public sealed partial class Timestamp : pb::IMessage<Timestamp> {
private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp());
@@ -130,7 +128,7 @@ namespace Google.Protobuf.WellKnownTypes {
private long seconds_;
/// <summary>
/// Represents seconds of UTC time since Unix epoch
- /// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
+ /// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
/// 9999-12-31T23:59:59Z inclusive.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
index 2bad3432..e6363480 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs
@@ -55,7 +55,7 @@ namespace Google.Protobuf.WellKnownTypes {
"IjsKBk9wdGlvbhIMCgRuYW1lGAEgASgJEiMKBXZhbHVlGAIgASgLMhQuZ29v",
"Z2xlLnByb3RvYnVmLkFueSouCgZTeW50YXgSEQoNU1lOVEFYX1BST1RPMhAA",
"EhEKDVNZTlRBWF9QUk9UTzMQAUJMChNjb20uZ29vZ2xlLnByb3RvYnVmQglU",
- "eXBlUHJvdG9QAaABAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25v",
+ "eXBlUHJvdG9QAfgBAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25v",
"d25UeXBlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.SourceContextReflection.Descriptor, },
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs
index 80f9f98d..e97c3d14 100644
--- a/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs
+++ b/csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs
@@ -28,10 +28,10 @@ namespace Google.Protobuf.WellKnownTypes {
"KAMiHAoLVUludDY0VmFsdWUSDQoFdmFsdWUYASABKAQiGwoKSW50MzJWYWx1",
"ZRINCgV2YWx1ZRgBIAEoBSIcCgtVSW50MzJWYWx1ZRINCgV2YWx1ZRgBIAEo",
"DSIaCglCb29sVmFsdWUSDQoFdmFsdWUYASABKAgiHAoLU3RyaW5nVmFsdWUS",
- "DQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEJ/",
+ "DQoFdmFsdWUYASABKAkiGwoKQnl0ZXNWYWx1ZRINCgV2YWx1ZRgBIAEoDEJ8",
"ChNjb20uZ29vZ2xlLnByb3RvYnVmQg1XcmFwcGVyc1Byb3RvUAFaKmdpdGh1",
- "Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy93cmFwcGVyc6ABAfgBAaIC",
- "A0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z"));
+ "Yi5jb20vZ29sYW5nL3Byb3RvYnVmL3B0eXBlcy93cmFwcGVyc/gBAaICA0dQ",
+ "QqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
diff --git a/csharp/src/Google.Protobuf/project.json b/csharp/src/Google.Protobuf/project.json
index 9b831f12..12e86248 100644
--- a/csharp/src/Google.Protobuf/project.json
+++ b/csharp/src/Google.Protobuf/project.json
@@ -1,5 +1,5 @@
{
- "version": "3.0.0",
+ "version": "3.1.0",
"title": "Google Protocol Buffers",
"description": "See project site for more info.",
"authors": [ "Google Inc." ],
diff --git a/docs/swift/DesignDoc.md b/docs/swift/DesignDoc.md
deleted file mode 100644
index 364a4d3f..00000000
--- a/docs/swift/DesignDoc.md
+++ /dev/null
@@ -1,674 +0,0 @@
-# Protocol Buffers in Swift
-
-## Objective
-
-This document describes the user-facing API and internal implementation of
-proto2 and proto3 messages in Apple’s Swift programming language.
-
-One of the key goals of protobufs is to provide idiomatic APIs for each
-language. In that vein, **interoperability with Objective-C is a non-goal of
-this proposal.** Protobuf users who need to pass messages between Objective-C
-and Swift code in the same application should use the existing Objective-C proto
-library. The goal of the effort described here is to provide an API for protobuf
-messages that uses features specific to Swift—optional types, algebraic
-enumerated types, value types, and so forth—in a natural way that will delight,
-rather than surprise, users of the language.
-
-## Naming
-
-* By convention, both typical protobuf message names and Swift structs/classes
- are `UpperCamelCase`, so for most messages, the name of a message can be the
- same as the name of its generated type. (However, see the discussion below
- about prefixes under [Packages](#packages).)
-
-* Enum cases in protobufs typically are `UPPERCASE_WITH_UNDERSCORES`, whereas
- in Swift they are `lowerCamelCase` (as of the Swift 3 API design
- guidelines). We will transform the names to match Swift convention, using
- a whitelist similar to the Objective-C compiler plugin to handle commonly
- used acronyms.
-
-* Typical fields in proto messages are `lowercase_with_underscores`, while in
- Swift they are `lowerCamelCase`. We will transform the names to match
- Swift convention by removing the underscores and uppercasing the subsequent
- letter.
-
-## Swift reserved words
-
-Swift has a large set of reserved words—some always reserved and some
-contextually reserved (that is, they can be used as identifiers in contexts
-where they would not be confused). As of Swift 2.2, the set of always-reserved
-words is:
-
-```
-_, #available, #column, #else, #elseif, #endif, #file, #function, #if, #line,
-#selector, as, associatedtype, break, case, catch, class, continue, default,
-defer, deinit, do, dynamicType, else, enum, extension, fallthrough, false, for,
-func, guard, if, import, in, init, inout, internal, is, let, nil, operator,
-private, protocol, public, repeat, rethrows, return, self, Self, static,
-struct, subscript, super, switch, throw, throws, true, try, typealias, var,
-where, while
-```
-
-The set of contextually reserved words is:
-
-```
-associativity, convenience, dynamic, didSet, final, get, infix, indirect,
-lazy, left, mutating, none, nonmutating, optional, override, postfix,
-precedence, prefix, Protocol, required, right, set, Type, unowned, weak,
-willSet
-```
-
-It is possible to use any reserved word as an identifier by escaping it with
-backticks (for example, ``let `class` = 5``). Other name-mangling schemes would
-require us to transform the names themselves (for example, by appending an
-underscore), which requires us to then ensure that the new name does not collide
-with something else in the same namespace.
-
-While the backtick feature may not be widely known by all Swift developers, a
-small amount of user education can address this and it seems like the best
-approach. We can unconditionally surround all property names with backticks to
-simplify generation.
-
-Some remapping will still be required, though, to avoid collisions between
-generated properties and the names of methods and properties defined in the base
-protocol/implementation of messages.
-
-# Features of Protocol Buffers
-
-This section describes how the features of the protocol buffer syntaxes (proto2
-and proto3) map to features in Swift—what the code generated from a proto will
-look like, and how it will be implemented in the underlying library.
-
-## Packages
-
-Modules are the main form of namespacing in Swift, but they are not declared
-using syntactic constructs like namespaces in C++ or packages in Java. Instead,
-they are tied to build targets in Xcode (or, in the future with open-source
-Swift, declarations in a Swift Package Manager manifest). They also do not
-easily support nesting submodules (Clang module maps support this, but pure
-Swift does not yet provide a way to define submodules).
-
-We will generate types with fully-qualified underscore-delimited names. For
-example, a message `Baz` in package `foo.bar` would generate a struct named
-`Foo_Bar_Baz`. For each fully-qualified proto message, there will be exactly one
-unique type symbol emitted in the generated binary.
-
-Users are likely to balk at the ugliness of underscore-delimited names for every
-generated type. To improve upon this situation, we will add a new string file
-level option, `swift_package_typealias`, that can be added to `.proto` files.
-When present, this will cause `typealias`es to be added to the generated Swift
-messages that replace the package name prefix with the provided string. For
-example, the following `.proto` file:
-
-```protobuf
-option swift_package_typealias = "FBP";
-package foo.bar;
-
-message Baz {
- // Message fields
-}
-```
-
-would generate the following Swift source:
-
-```swift
-public struct Foo_Bar_Baz {
- // Message fields and other methods
-}
-
-typealias FBPBaz = Foo_Bar_Baz
-```
-
-It should be noted that this type alias is recorded in the generated
-`.swiftmodule` so that code importing the module can refer to it, but it does
-not cause a new symbol to be generated in the compiled binary (i.e., we do not
-risk compiled size bloat by adding `typealias`es for every type).
-
-Other strategies to handle packages that were considered and rejected can be
-found in [Appendix A](#appendix-a-rejected-strategies-to-handle-packages).
-
-## Messages
-
-Proto messages are natural value types and we will generate messages as structs
-instead of classes. Users will benefit from Swift’s built-in behavior with
-regard to mutability. We will define a `ProtoMessage` protocol that defines the
-common methods and properties for all messages (such as serialization) and also
-lets users treat messages polymorphically. Any shared method implementations
-that do not differ between individual messages can be implemented in a protocol
-extension.
-
-The backing storage itself for fields of a message will be managed by a
-`ProtoFieldStorage` type that uses an internal dictionary keyed by field number,
-and whose values are the value of the field with that number (up-cast to Swift’s
-`Any` type). This class will provide type-safe getters and setters so that
-generated messages can manipulate this storage, and core serialization logic
-will live here as well. Furthermore, factoring the storage out into a separate
-type, rather than inlining the fields as stored properties in the message
-itself, lets us implement copy-on-write efficiently to support passing around
-large messages. (Furthermore, because the messages themselves are value types,
-inlining fields is not possible if the fields are submessages of the same type,
-or a type that eventually includes a submessage of the same type.)
-
-### Required fields (proto2 only)
-
-Required fields in proto2 messages seem like they could be naturally represented
-by non-optional properties in Swift, but this presents some problems/concerns.
-
-Serialization APIs permit partial serialization, which allows required fields to
-remain unset. Furthermore, other language APIs still provide `has*` and `clear*`
-methods for required fields, and knowing whether a property has a value when the
-message is in memory is still useful.
-
-For example, an e-mail draft message may have the “to” address required on the
-wire, but when the user constructs it in memory, it doesn’t make sense to force
-a value until they provide one. We only want to force a value to be present when
-the message is serialized to the wire. Using non-optional properties prevents
-this use case, and makes client usage awkward because the user would be forced
-to select a sentinel or placeholder value for any required fields at the time
-the message was created.
-
-### Default values
-
-In proto2, fields can have a default value specified that may be a value other
-than the default value for its corresponding language type (for example, a
-default value of 5 instead of 0 for an integer). When reading a field that is
-not explicitly set, the user expects to get that value. This makes Swift
-optionals (i.e., `Foo?`) unsuitable for fields in general. Unfortunately, we
-cannot implement our own “enhanced optional” type without severely complicating
-usage (Swift’s use of type inference and its lack of implicit conversions would
-require manual unwrapping of every property value).
-
-Instead, we can use **implicitly unwrapped optionals.** For example, a property
-generated for a field of type `int32` would have Swift type `Int32!`. These
-properties would behave with the following characteristics, which mirror the
-nil-resettable properties used elsewhere in Apple’s SDKs (for example,
-`UIView.tintColor`):
-
-* Assigning a non-nil value to a property sets the field to that value.
-* Assigning nil to a property clears the field (its internal representation is
- nilled out).
-* Reading the value of a property returns its value if it is set, or returns
- its default value if it is not set. Reading a property never returns nil.
-
-The final point in the list above implies that the optional cannot be checked to
-determine if the field is set to a value other than its default: it will never
-be nil. Instead, we must provide `has*` methods for each field to allow the user
-to check this. These methods will be public in proto2. In proto3, these methods
-will be private (if generated at all), since the user can test the returned
-value against the zero value for that type.
-
-### Autocreation of nested messages
-
-For convenience, dotting into an unset field representing a nested message will
-return an instance of that message with default values. As in the Objective-C
-implementation, this does not actually cause the field to be set until the
-returned message is mutated. Fortunately, thanks to the way mutability of value
-types is implemented in Swift, the language automatically handles the
-reassignment-on-mutation for us. A static singleton instance containing default
-values can be associated with each message that can be returned when reading, so
-copies are only made by the Swift runtime when mutation occurs. For example,
-given the following proto:
-
-```protobuf
-message Node {
- Node child = 1;
- string value = 2 [default = "foo"];
-}
-```
-
-The following Swift code would act as commented, where setting deeply nested
-properties causes the copies and mutations to occur as the assignment statement
-is unwound:
-
-```swift
-var node = Node()
-
-let s = node.child.child.value
-// 1. node.child returns the "default Node".
-// 2. Reading .child on the result of (1) returns the same default Node.
-// 3. Reading .value on the result of (2) returns the default value "foo".
-
-node.child.child.value = "bar"
-// 4. Setting .value on the default Node causes a copy to be made and sets
-// the property on that copy. Subsequently, the language updates the
-// value of "node.child.child" to point to that copy.
-// 5. Updating "node.child.child" in (4) requires another copy, because
-// "node.child" was also the instance of the default node. The copy is
-// assigned back to "node.child".
-// 6. Setting "node.child" in (5) is a simple value reassignment, since
-// "node" is a mutable var.
-```
-
-In other words, the generated messages do not internally have to manage parental
-relationships to backfill the appropriate properties on mutation. Swift provides
-this for free.
-
-## Scalar value fields
-
-Proto scalar value fields will map to Swift types in the following way:
-
-.proto Type | Swift Type
------------ | -------------------
-`double` | `Double`
-`float` | `Float`
-`int32` | `Int32`
-`int64` | `Int64`
-`uint32` | `UInt32`
-`uint64` | `UInt64`
-`sint32` | `Int32`
-`sint64` | `Int64`
-`fixed32` | `UInt32`
-`fixed64` | `UInt64`
-`sfixed32` | `Int32`
-`sfixed64` | `Int64`
-`bool` | `Bool`
-`string` | `String`
-`bytes` | `Foundation.NSData`
-
-The proto spec defines a number of integral types that map to the same Swift
-type; for example, `intXX`, `sintXX`, and `sfixedXX` are all signed integers,
-and `uintXX` and `fixedXX` are both unsigned integers. No other language
-implementation distinguishes these further, so we do not do so either. The
-rationale is that the various types only serve to distinguish how the value is
-**encoded on the wire**; once loaded in memory, the user is not concerned about
-these variations.
-
-Swift’s lack of implicit conversions among types will make it slightly annoying
-to use these types in a context expecting an `Int`, or vice-versa, but since
-this is a data-interchange format with explicitly-sized fields, we should not
-hide that information from the user. Users will have to explicitly write
-`Int(message.myField)`, for example.
-
-## Embedded message fields
-
-Embedded message fields can be represented using an optional variable of the
-generated message type. Thus, the message
-
-```protobuf
-message Foo {
- Bar bar = 1;
-}
-```
-
-would be represented in Swift as
-
-```swift
-public struct Foo: ProtoMessage {
- public var bar: Bar! {
- get { ... }
- set { ... }
- }
-}
-```
-
-If the user explicitly sets `bar` to nil, or if it was never set when read from
-the wire, retrieving the value of `bar` would return a default, statically
-allocated instance of `Bar` containing default values for its fields. This
-achieves the desired behavior for default values in the same way that scalar
-fields are designed, and also allows users to deep-drill into complex object
-graphs to get or set fields without checking for nil at each step.
-
-## Enum fields
-
-The design and implementation of enum fields will differ somewhat drastically
-depending on whether the message being generated is a proto2 or proto3 message.
-
-### proto2 enums
-
-For proto2, we do not need to be concerned about unknown enum values, so we can
-use the simple raw-value enum syntax provided by Swift. So the following enum in
-proto2:
-
-```protobuf
-enum ContentType {
- TEXT = 0;
- IMAGE = 1;
-}
-```
-
-would become this Swift enum:
-
-```swift
-public enum ContentType: Int32, NilLiteralConvertible {
- case text = 0
- case image = 1
-
- public init(nilLiteral: ()) {
- self = .text
- }
-}
-```
-
-See below for the discussion about `NilLiteralConvertible`.
-
-### proto3 enums
-
-For proto3, we need to be able to preserve unknown enum values that may come
-across the wire so that they can be written back if unmodified. We can
-accomplish this in Swift by using a case with an associated value for unknowns.
-So the following enum in proto3:
-
-```protobuf
-enum ContentType {
- TEXT = 0;
- IMAGE = 1;
-}
-```
-
-would become this Swift enum:
-
-```swift
-public enum ContentType: RawRepresentable, NilLiteralConvertible {
- case text
- case image
- case UNKNOWN_VALUE(Int32)
-
- public typealias RawValue = Int32
-
- public init(nilLiteral: ()) {
- self = .text
- }
-
- public init(rawValue: RawValue) {
- switch rawValue {
- case 0: self = .text
- case 1: self = .image
- default: self = .UNKNOWN_VALUE(rawValue)
- }
-
- public var rawValue: RawValue {
- switch self {
- case .text: return 0
- case .image: return 1
- case .UNKNOWN_VALUE(let value): return value
- }
- }
-}
-```
-
-Note that the use of a parameterized case prevents us from inheriting from the
-raw `Int32` type; Swift does not allow an enum with a raw type to have cases
-with arguments. Instead, we must implement the raw value initializer and
-computed property manually. The `UNKNOWN_VALUE` case is explicitly chosen to be
-"ugly" so that it stands out and does not conflict with other possible case
-names.
-
-Using this approach, proto3 consumers must always have a default case or handle
-the `.UNKNOWN_VALUE` case to satisfy case exhaustion in a switch statement; the
-Swift compiler considers it an error if switch statements are not exhaustive.
-
-### NilLiteralConvertible conformance
-
-This is required to clean up the usage of enum-typed properties in switch
-statements. Unlike other field types, enum properties cannot be
-implicitly-unwrapped optionals without requiring that uses in switch statements
-be explicitly unwrapped. For example, if we consider a message with the enum
-above, this usage will fail to compile:
-
-```swift
-// Without NilLiteralConvertible conformance on ContentType
-public struct SomeMessage: ProtoMessage {
- public var contentType: ContentType! { ... }
-}
-
-// ERROR: no case named text or image
-switch someMessage.contentType {
- case .text: { ... }
- case .image: { ... }
-}
-```
-
-Even though our implementation guarantees that `contentType` will never be nil,
-if it is an optional type, its cases would be `some` and `none`, not the cases
-of the underlying enum type. In order to use it in this context, the user must
-write `someMessage.contentType!` in their switch statement.
-
-Making the enum itself `NilLiteralConvertible` permits us to make the property
-non-optional, so the user can still set it to nil to clear it (i.e., reset it to
-its default value), while eliminating the need to explicitly unwrap it in a
-switch statement.
-
-```swift
-// With NilLiteralConvertible conformance on ContentType
-public struct SomeMessage: ProtoMessage {
- // Note that the property type is no longer optional
- public var contentType: ContentType { ... }
-}
-
-// OK: Compiles and runs as expected
-switch someMessage.contentType {
- case .text: { ... }
- case .image: { ... }
-}
-
-// The enum can be reset to its default value this way
-someMessage.contentType = nil
-```
-
-One minor oddity with this approach is that nil will be auto-converted to the
-default value of the enum in any context, not just field assignment. In other
-words, this is valid:
-
-```swift
-func foo(contentType: ContentType) { ... }
-foo(nil) // Inside foo, contentType == .text
-```
-
-That being said, the advantage of being able to simultaneously support
-nil-resettability and switch-without-unwrapping outweighs this side effect,
-especially if appropriately documented. It is our hope that a new form of
-resettable properties will be added to Swift that eliminates this inconsistency.
-Some community members have already drafted or sent proposals for review that
-would benefit our designs:
-
-* [SE-0030: Property Behaviors]
- (https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md)
-* [Drafted: Resettable Properties]
- (https://github.com/patters/swift-evolution/blob/master/proposals/0000-resettable-properties.md)
-
-### Enum aliases
-
-The `allow_alias` option in protobuf slightly complicates the use of Swift enums
-to represent that type, because raw values of cases in an enum must be unique.
-Swift lets us define static variables in an enum that alias actual cases. For
-example, the following protobuf enum:
-
-```protobuf
-enum Foo {
- option allow_alias = true;
- BAR = 0;
- BAZ = 0;
-}
-```
-
-will be represented in Swift as:
-
-```swift
-public enum Foo: Int32, NilLiteralConvertible {
- case bar = 0
- static public let baz = bar
-
- // ... etc.
-}
-
-// Can still use .baz shorthand to reference the alias in contexts
-// where the type is inferred
-```
-
-That is, we use the first name as the actual case and use static variables for
-the other aliases. One drawback to this approach is that the static aliases
-cannot be used as cases in a switch statement (the compiler emits the error
-*“Enum case ‘baz’ not found in type ‘Foo’”*). However, in our own code bases,
-there are only a few places where enum aliases are not mere renamings of an
-older value, but they also don’t appear to be the type of value that one would
-expect to switch on (for example, a group of named constants representing
-metrics rather than a set of options), so this restriction is not significant.
-
-This strategy also implies that changing the name of an enum and adding the old
-name as an alias below the new name will be a breaking change in the generated
-Swift code.
-
-## Oneof types
-
-The `oneof` feature represents a “variant/union” data type that maps nicely to
-Swift enums with associated values (algebraic types). These fields can also be
-accessed independently though, and, specifically in the case of proto2, it’s
-reasonable to expect access to default values when accessing a field that is not
-explicitly set.
-
-Taking all this into account, we can represent a `oneof` in Swift with two sets
-of constructs:
-
-* Properties in the message that correspond to the `oneof` fields.
-* A nested enum named after the `oneof` and which provides the corresponding
- field values as case arguments.
-
-This approach fulfills the needs of proto consumers by providing a
-Swift-idiomatic way of simultaneously checking which field is set and accessing
-its value, providing individual properties to access the default values
-(important for proto2), and safely allows a field to be moved into a `oneof`
-without breaking clients.
-
-Consider the following proto:
-
-```protobuf
-message MyMessage {
- oneof record {
- string name = 1 [default = "unnamed"];
- int32 id_number = 2 [default = 0];
- }
-}
-```
-
-In Swift, we would generate an enum, a property for that enum, and properties
-for the fields themselves:
-
-```swift
-public struct MyMessage: ProtoMessage {
- public enum Record: NilLiteralConvertible {
- case name(String)
- case idNumber(Int32)
- case NOT_SET
-
- public init(nilLiteral: ()) { self = .NOT_SET }
- }
-
- // This is the "Swifty" way of accessing the value
- public var record: Record { ... }
-
- // Direct access to the underlying fields
- public var name: String! { ... }
- public var idNumber: Int32! { ... }
-}
-```
-
-This makes both usage patterns possible:
-
-```swift
-// Usage 1: Case-based dispatch
-switch message.record {
- case .name(let name):
- // Do something with name if it was explicitly set
- case .idNumber(let id):
- // Do something with id_number if it was explicitly set
- case .NOT_SET:
- // Do something if it’s not set
-}
-
-// Usage 2: Direct access for default value fallback
-// Sets the label text to the name if it was explicitly set, or to
-// "unnamed" (the default value for the field) if id_number was set
-// instead
-let myLabel = UILabel()
-myLabel.text = message.name
-```
-
-As with proto enums, the generated `oneof` enum conforms to
-`NilLiteralConvertible` to avoid switch statement issues. Setting the property
-to nil will clear it (i.e., reset it to `NOT_SET`).
-
-## Unknown Fields (proto2 only)
-
-To be written.
-
-## Extensions (proto2 only)
-
-To be written.
-
-## Reflection and Descriptors
-
-We will not include reflection or descriptors in the first version of the Swift
-library. The use cases for reflection on mobile are not as strong and the static
-data to represent the descriptors would add bloat when we wish to keep the code
-size small.
-
-In the future, we will investigate whether they can be included as extensions
-which might be able to be excluded from a build and/or automatically dead
-stripped by the compiler if they are not used.
-
-## Appendix A: Rejected strategies to handle packages
-
-### Each package is its own Swift module
-
-Each proto package could be declared as its own Swift module, replacing dots
-with underscores (e.g., package `foo.bar` becomes module `Foo_Bar`). Then, users
-would simply import modules containing whatever proto modules they want to use
-and refer to the generated types by their short names.
-
-**This solution is simply not possible, however.** Swift modules cannot
-circularly reference each other, but there is no restriction against proto
-packages doing so. Circular imports are forbidden (e.g., `foo.proto` importing
-`bar.proto` importing `foo.proto`), but nothing prevents package `foo` from
-using a type in package `bar` which uses a different type in package `foo`, as
-long as there is no import cycle. If these packages were generated as Swift
-modules, then `Foo` would contain an `import Bar` statement and `Bar` would
-contain an `import Foo` statement, and there is no way to compile this.
-
-### Ad hoc namespacing with structs
-
-We can “fake” namespaces in Swift by declaring empty structs with private
-initializers. Since modules are constructed based on compiler arguments, not by
-syntactic constructs, and because there is no pure Swift way to define
-submodules (even though Clang module maps support this), there is no
-source-drive way to group generated code into namespaces aside from this
-approach.
-
-Types can be added to those intermediate package structs using Swift extensions.
-For example, a message `Baz` in package `foo.bar` could be represented in Swift
-as follows:
-
-```swift
-public struct Foo {
- private init() {}
-}
-
-public extension Foo {
- public struct Bar {
- private init() {}
- }
-}
-
-public extension Foo.Bar {
- public struct Baz {
- // Message fields and other methods
- }
-}
-
-let baz = Foo.Bar.Baz()
-```
-
-Each of these constructs would actually be defined in a separate file; Swift
-lets us keep them separate and add multiple structs to a single “namespace”
-through extensions.
-
-Unfortunately, these intermediate structs generate symbols of their own
-(metatype information in the data segment). This becomes problematic if multiple
-build targets contain Swift sources generated from different messages in the
-same package. At link time, these symbols would collide, resulting in multiple
-definition errors.
-
-This approach also has the disadvantage that there is no automatic “short” way
-to refer to the generated messages at the deepest nesting levels; since this use
-of structs is a hack around the lack of namespaces, there is no equivalent to
-import (Java) or using (C++) to simplify this. Users would have to declare type
-aliases to make this cleaner, or we would have to generate them for users.
diff --git a/docs/third_party.md b/docs/third_party.md
index 021cc564..161bc3ca 100644
--- a/docs/third_party.md
+++ b/docs/third_party.md
@@ -36,6 +36,7 @@ These are projects we know about implementing Protocol Buffers for other program
* Erlang: http://piqi.org/
* Erlang: https://code.google.com/p/protoc-gen-erl/
* Erlang: https://github.com/basho/erlang_protobuffs
+* Erlang: https://github.com/tomas-abrahamsson/gpb
* Go: https://github.com/golang/protobuf (Google-official implementation)
* Go: http://code.google.com/p/goprotobuf/
* Go: https://github.com/akunspy/gopbuf
@@ -45,7 +46,6 @@ These are projects we know about implementing Protocol Buffers for other program
* Java/Android: https://github.com/square/wire
* Java ME: http://code.google.com/p/protobuf-javame/
* Java ME: http://swingme.sourceforge.net/encode.shtml
-* Java ME: http://github.com/ponderingpanda/protobuf-j2me
* Java ME: http://code.google.com/p/protobuf-j2me/
* Javascript: http://code.google.com/p/protobuf-js/
* Javascript: http://github.com/sirikata/protojs
@@ -63,6 +63,7 @@ These are projects we know about implementing Protocol Buffers for other program
* OCaml: http://piqi.org/
* Perl: http://groups.google.com/group/protobuf-perl
* Perl: http://search.cpan.org/perldoc?Google::ProtocolBuffers
+* Perl: https://metacpan.org/pod/Google::ProtocolBuffers::Dynamic
* Perl/XS: http://code.google.com/p/protobuf-perlxs/
* PHP: http://code.google.com/p/pb4php/
* PHP: https://github.com/allegro/php-protobuf/
@@ -82,6 +83,7 @@ These are projects we know about implementing Protocol Buffers for other program
* Scala: https://github.com/SandroGrzicic/ScalaBuff
* Scala: http://trueaccord.github.io/ScalaPB/
* Swift: https://github.com/alexeyxo/protobuf-swift
+* Swift: https://github.com/apple/swift-protobuf/
* Vala: https://launchpad.net/protobuf-vala
* Visual Basic: http://code.google.com/p/protobuf-net/
diff --git a/editors/protobuf-mode.el b/editors/protobuf-mode.el
index f615a0af..1cef4137 100644
--- a/editors/protobuf-mode.el
+++ b/editors/protobuf-mode.el
@@ -64,12 +64,13 @@
;;; Code:
(require 'cc-mode)
+(require 'cl)
(eval-when-compile
(require 'cc-langs)
(require 'cc-fonts))
-;; This mode does not inherit properties from other modes. So, we do not use
+;; This mode does not inherit properties from other modes. So, we do not use
;; the usual `c-add-language' function.
(eval-and-compile
(put 'protobuf-mode 'c-mode-prefix "protobuf-"))
diff --git a/generate_changelog.py b/generate_changelog.py
new file mode 100755
index 00000000..d7575d46
--- /dev/null
+++ b/generate_changelog.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+
+"""Generates a friendly list of changes per language since the last release."""
+
+import sys
+import os
+
+class Language(object):
+ def __init__(self, name, pathspec):
+ self.name = name
+ self.pathspec = pathspec
+
+languages = [
+ Language("C++", [
+ "':(glob)src/google/protobuf/*'",
+ "src/google/protobuf/compiler/cpp",
+ "src/google/protobuf/io",
+ "src/google/protobuf/util",
+ "src/google/protobuf/stubs",
+ ]),
+ Language("Java", [
+ "java",
+ "javanano",
+ "src/google/protobuf/compiler/cpp",
+ ]),
+ Language("Python", [
+ "javanano",
+ "src/google/protobuf/compiler/python",
+ ]),
+ Language("JavaScript", [
+ "js",
+ "src/google/protobuf/compiler/js",
+ ]),
+ Language("PHP", [
+ "php",
+ "src/google/protobuf/compiler/php",
+ ]),
+ Language("Ruby", [
+ "ruby",
+ "src/google/protobuf/compiler/ruby",
+ ]),
+ Language("Csharp", [
+ "csharp",
+ "src/google/protobuf/compiler/csharp",
+ ]),
+ Language("Objective C", [
+ "objectivec",
+ "src/google/protobuf/compiler/objectivec",
+ ]),
+]
+
+if len(sys.argv) < 2:
+ print("Usage: generate_changelog.py <previous release>")
+ sys.exit(1)
+
+previous = sys.argv[1]
+
+for language in languages:
+ print(language.name)
+ os.system(("git log --pretty=oneline --abbrev-commit %s...HEAD %s | " +
+ "sed -e 's/^/ - /'") % (previous, " ".join(language.pathspec)))
+ print("")
+
+print("To view a commit on GitHub: " +
+ "https://github.com/google/protobuf/commit/<commit id>")
diff --git a/generate_descriptor_proto.sh b/generate_descriptor_proto.sh
index c170c837..668e6d13 100755
--- a/generate_descriptor_proto.sh
+++ b/generate_descriptor_proto.sh
@@ -1,4 +1,4 @@
-#!/bin/sh
+#!/usr/bin/env bash
# Run this script to regenerate descriptor.pb.{h,cc} after the protocol
# compiler changes. Since these files are compiled into the protocol compiler
diff --git a/gmock.BUILD b/gmock.BUILD
index 82abf275..b1ae15a9 100644
--- a/gmock.BUILD
+++ b/gmock.BUILD
@@ -1,19 +1,19 @@
cc_library(
name = "gtest",
srcs = [
- "gmock-1.7.0/gtest/src/gtest-all.cc",
- "gmock-1.7.0/src/gmock-all.cc",
+ "googletest/src/gtest-all.cc",
+ "googlemock/src/gmock-all.cc",
],
hdrs = glob([
- "gmock-1.7.0/**/*.h",
- "gmock-1.7.0/gtest/src/*.cc",
- "gmock-1.7.0/src/*.cc",
+ "**/*.h",
+ "googletest/src/*.cc",
+ "googlemock/src/*.cc",
]),
includes = [
- "gmock-1.7.0",
- "gmock-1.7.0/gtest",
- "gmock-1.7.0/gtest/include",
- "gmock-1.7.0/include",
+ "googlemock",
+ "googletest",
+ "googletest/include",
+ "googlemock/include",
],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
@@ -21,7 +21,7 @@ cc_library(
cc_library(
name = "gtest_main",
- srcs = ["gmock-1.7.0/src/gmock_main.cc"],
+ srcs = ["googlemock/src/gmock_main.cc"],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
deps = [":gtest"],
diff --git a/java/compatibility_tests/v2.5.0/protos/pom.xml b/java/compatibility_tests/v2.5.0/protos/pom.xml
index 24447bdc..a22e91ed 100644
--- a/java/compatibility_tests/v2.5.0/protos/pom.xml
+++ b/java/compatibility_tests/v2.5.0/protos/pom.xml
@@ -28,7 +28,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
- <version>3.3</version>
+ <version>3.6.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
diff --git a/java/core/pom.xml b/java/core/pom.xml
index 39d67818..cced344e 100644
--- a/java/core/pom.xml
+++ b/java/core/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.0.0</version>
+ <version>3.1.0</version>
</parent>
<artifactId>protobuf-java</artifactId>
@@ -92,11 +92,34 @@
<!-- Add the generated sources to the build -->
<plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <generatedSourcesDirectory>${generated.sources.dir}</generatedSourcesDirectory>
- <generatedTestSourcesDirectory>${generated.testsources.dir}</generatedTestSourcesDirectory>
- </configuration>
+ <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.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.dir}</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
</plugin>
<!-- OSGI bundle configuration -->
diff --git a/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java b/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java
index 0cc38175..6157a52f 100644
--- a/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java
+++ b/java/core/src/main/java/com/google/protobuf/ByteBufferWriter.java
@@ -33,11 +33,12 @@ package com.google.protobuf;
import static java.lang.Math.max;
import static java.lang.Math.min;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
+import java.lang.reflect.Field;
import java.nio.ByteBuffer;
+import java.nio.channels.WritableByteChannel;
/**
* Utility class to provide efficient writing of {@link ByteBuffer}s to {@link OutputStream}s.
@@ -75,6 +76,12 @@ final class ByteBufferWriter {
new ThreadLocal<SoftReference<byte[]>>();
/**
+ * This is a hack for GAE, where {@code FileOutputStream} is unavailable.
+ */
+ private static final Class<?> FILE_OUTPUT_STREAM_CLASS = safeGetClass("java.io.FileOutputStream");
+ private static final long CHANNEL_FIELD_OFFSET = getChannelFieldOffset(FILE_OUTPUT_STREAM_CLASS);
+
+ /**
* For testing purposes only. Clears the cached buffer to force a new allocation on the next
* invocation.
*/
@@ -93,10 +100,7 @@ final class ByteBufferWriter {
// Optimized write for array-backed buffers.
// Note that we're taking the risk that a malicious OutputStream could modify the array.
output.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
- } else if (output instanceof FileOutputStream) {
- // Use a channel to write out the ByteBuffer. This will automatically empty the buffer.
- ((FileOutputStream) output).getChannel().write(buffer);
- } else {
+ } else if (!writeToChannel(buffer, output)){
// Read all of the data from the buffer to an array.
// TODO(nathanmittler): Consider performance improvements for other "known" stream types.
final byte[] array = getOrCreateBuffer(buffer.remaining());
@@ -142,4 +146,40 @@ final class ByteBufferWriter {
private static void setBuffer(byte[] value) {
BUFFER.set(new SoftReference<byte[]>(value));
}
+
+ private static boolean writeToChannel(ByteBuffer buffer, OutputStream output) throws IOException {
+ if (CHANNEL_FIELD_OFFSET >= 0 && FILE_OUTPUT_STREAM_CLASS.isInstance(output)) {
+ // Use a channel to write out the ByteBuffer. This will automatically empty the buffer.
+ WritableByteChannel channel = null;
+ try {
+ channel = (WritableByteChannel) UnsafeUtil.getObject(output, CHANNEL_FIELD_OFFSET);
+ } catch (ClassCastException e) {
+ // Absorb.
+ }
+ if (channel != null) {
+ channel.write(buffer);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static Class<?> safeGetClass(String className) {
+ try {
+ return Class.forName(className);
+ } catch (ClassNotFoundException e) {
+ return null;
+ }
+ }
+ private static long getChannelFieldOffset(Class<?> clazz) {
+ try {
+ if (clazz != null && UnsafeUtil.hasUnsafeArrayOperations()) {
+ Field field = clazz.getDeclaredField("channel");
+ return UnsafeUtil.objectFieldOffset(field);
+ }
+ } catch (Throwable e) {
+ // Absorb
+ }
+ return -1;
+ }
}
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 49653899..5b24976d 100644
--- a/java/core/src/main/java/com/google/protobuf/ByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/ByteString.java
@@ -52,9 +52,9 @@ import java.util.NoSuchElementException;
/**
* Immutable sequence of bytes. Substring is supported by sharing the reference
- * to the immutable underlying bytes, as with {@link String}. Concatenation is
- * likewise supported without copying (long strings) by building a tree of
- * pieces in {@link RopeByteString}.
+ * to the immutable underlying bytes. Concatenation is likewise supported
+ * without copying (long strings) by building a tree of pieces in
+ * {@link RopeByteString}.
* <p>
* Like {@link String}, the contents of a {@link ByteString} can never be
* observed to change, not even in the presence of a data race or incorrect
@@ -311,6 +311,18 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
}
/**
+ * Wraps the given bytes into a {@code ByteString}. Intended for internal only usage.
+ */
+ static ByteString wrap(ByteBuffer buffer) {
+ if (buffer.hasArray()) {
+ final int offset = buffer.arrayOffset();
+ return ByteString.wrap(buffer.array(), offset + buffer.position(), buffer.remaining());
+ } else {
+ return new NioByteString(buffer);
+ }
+ }
+
+ /**
* Wraps the given bytes into a {@code ByteString}. Intended for internal only
* usage to force a classload of ByteString before LiteralByteString.
*/
@@ -679,6 +691,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
*/
abstract void writeTo(ByteOutput byteOutput) throws IOException;
+
/**
* Constructs a read-only {@code java.nio.ByteBuffer} whose content
* is equal to the contents of this byte string.
@@ -820,6 +833,7 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
return true;
}
+
/**
* Check equality of the substring of given length of this object starting at
* zero with another {@code ByteString} substring starting at offset.
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 e8860651..e461fa28 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedInputStream.java
@@ -30,6 +30,14 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.EMPTY_BYTE_ARRAY;
+import static com.google.protobuf.Internal.EMPTY_BYTE_BUFFER;
+import static com.google.protobuf.Internal.UTF_8;
+import static com.google.protobuf.Internal.checkNotNull;
+import static com.google.protobuf.WireFormat.FIXED_32_SIZE;
+import static com.google.protobuf.WireFormat.FIXED_64_SIZE;
+import static com.google.protobuf.WireFormat.MAX_VARINT_SIZE;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -41,51 +49,55 @@ import java.util.List;
/**
* 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.
+ * <p>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 CodedInputStream {
- /**
- * Create a new CodedInputStream wrapping the given InputStream.
- */
+public abstract class CodedInputStream {
+ private static final int DEFAULT_BUFFER_SIZE = 4096;
+ private static final int DEFAULT_RECURSION_LIMIT = 100;
+ private static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB
+
+ /** Visible for subclasses. See setRecursionLimit() */
+ int recursionDepth;
+
+ int recursionLimit = DEFAULT_RECURSION_LIMIT;
+
+ /** Visible for subclasses. See setSizeLimit() */
+ int sizeLimit = DEFAULT_SIZE_LIMIT;
+
+ /** Create a new CodedInputStream wrapping the given InputStream. */
public static CodedInputStream newInstance(final InputStream input) {
- return new CodedInputStream(input, BUFFER_SIZE);
+ return newInstance(input, DEFAULT_BUFFER_SIZE);
}
-
- /**
- * Create a new CodedInputStream wrapping the given InputStream.
- */
+
+ /** Create a new CodedInputStream wrapping the given InputStream. */
static CodedInputStream newInstance(final InputStream input, int bufferSize) {
- return new CodedInputStream(input, bufferSize);
+ if (input == null) {
+ // TODO(nathanmittler): Ideally we should throw here. This is done for backward compatibility.
+ return newInstance(EMPTY_BYTE_ARRAY);
+ }
+ return new StreamDecoder(input, bufferSize);
}
- /**
- * Create a new CodedInputStream wrapping the given byte array.
- */
+ /** Create a new CodedInputStream wrapping the given byte array. */
public static CodedInputStream newInstance(final byte[] buf) {
return newInstance(buf, 0, buf.length);
}
- /**
- * Create a new CodedInputStream wrapping the given byte array slice.
- */
- public static CodedInputStream newInstance(final byte[] buf, final int off,
- final int len) {
+ /** Create a new CodedInputStream wrapping the given byte array slice. */
+ public static CodedInputStream newInstance(final byte[] buf, final int off, final int len) {
return newInstance(buf, off, len, false /* bufferIsImmutable */);
}
-
- /**
- * Create a new CodedInputStream wrapping the given byte array slice.
- */
+
+ /** Create a new CodedInputStream wrapping the given byte array slice. */
static CodedInputStream newInstance(
final byte[] buf, final int off, final int len, final boolean bufferIsImmutable) {
- CodedInputStream result = new CodedInputStream(buf, off, len, bufferIsImmutable);
+ ArrayDecoder result = new ArrayDecoder(buf, off, len, bufferIsImmutable);
try {
// Some uses of CodedInputStream can be more efficient if they know
// exactly how many bytes are available. By pushing the end point of the
@@ -107,583 +119,358 @@ public final class CodedInputStream {
}
/**
- * Create a new CodedInputStream wrapping the given ByteBuffer. The data
- * starting from the ByteBuffer's current position to its limit will be read.
- * The returned CodedInputStream may or may not share the underlying data
- * in the ByteBuffer, therefore the ByteBuffer cannot be changed while the
- * CodedInputStream is in use.
- * Note that the ByteBuffer's position won't be changed by this function.
- * Concurrent calls with the same ByteBuffer object are safe if no other
- * thread is trying to alter the ByteBuffer's status.
+ * Create a new CodedInputStream wrapping the given ByteBuffer. The data starting from the
+ * ByteBuffer's current position to its limit will be read. The returned CodedInputStream may or
+ * may not share the underlying data in the ByteBuffer, therefore the ByteBuffer cannot be changed
+ * while the CodedInputStream is in use. Note that the ByteBuffer's position won't be changed by
+ * this function. Concurrent calls with the same ByteBuffer object are safe if no other thread is
+ * trying to alter the ByteBuffer's status.
*/
public static CodedInputStream newInstance(ByteBuffer buf) {
+ return newInstance(buf, false /* bufferIsImmutable */);
+ }
+
+ /** Create a new CodedInputStream wrapping the given buffer. */
+ static CodedInputStream newInstance(ByteBuffer buf, boolean bufferIsImmutable) {
if (buf.hasArray()) {
- return newInstance(buf.array(), buf.arrayOffset() + buf.position(),
- buf.remaining());
- } else {
- ByteBuffer temp = buf.duplicate();
- byte[] buffer = new byte[temp.remaining()];
- temp.get(buffer);
- return newInstance(buffer);
+ return newInstance(
+ buf.array(), buf.arrayOffset() + buf.position(), buf.remaining(), bufferIsImmutable);
+ }
+
+ if (buf.isDirect() && UnsafeDirectNioDecoder.isSupported()) {
+ return new UnsafeDirectNioDecoder(buf, bufferIsImmutable);
}
+
+ // The buffer is non-direct and does not expose the underlying array. Using the ByteBuffer API
+ // to access individual bytes is very slow, so just copy the buffer to an array.
+ // TODO(nathanmittler): Re-evaluate with Java 9
+ byte[] buffer = new byte[buf.remaining()];
+ buf.duplicate().get(buffer);
+ return newInstance(buffer, 0, buffer.length, true);
}
+ /** Disable construction/inheritance outside of this class. */
+ private CodedInputStream() {}
+
// -----------------------------------------------------------------
/**
- * 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.
+ * 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 (WireFormat.getTagFieldNumber(lastTag) == 0) {
- // If we actually read zero (or any tag number corresponding to field
- // number zero), that's not a valid tag.
- throw InvalidProtocolBufferException.invalidTag();
- }
- return lastTag;
- }
+ public abstract int readTag() throws IOException;
/**
- * 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.
+ * 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 InvalidProtocolBufferException {@code value} does not match the
- * last tag.
+ * @throws InvalidProtocolBufferException {@code value} does not match the last tag.
*/
- public void checkLastTagWas(final int value)
- throws InvalidProtocolBufferException {
- if (lastTag != value) {
- throw InvalidProtocolBufferException.invalidEndTag();
- }
- }
+ public abstract void checkLastTagWas(final int value) throws InvalidProtocolBufferException;
- public int getLastTag() {
- return lastTag;
- }
+ public abstract int getLastTag();
/**
* 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}.
+ * @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 (WireFormat.getTagWireType(tag)) {
- case WireFormat.WIRETYPE_VARINT:
- skipRawVarint();
- return true;
- case WireFormat.WIRETYPE_FIXED64:
- skipRawBytes(8);
- return true;
- case WireFormat.WIRETYPE_LENGTH_DELIMITED:
- skipRawBytes(readRawVarint32());
- return true;
- case WireFormat.WIRETYPE_START_GROUP:
- skipMessage();
- checkLastTagWas(
- WireFormat.makeTag(WireFormat.getTagFieldNumber(tag),
- WireFormat.WIRETYPE_END_GROUP));
- return true;
- case WireFormat.WIRETYPE_END_GROUP:
- return false;
- case WireFormat.WIRETYPE_FIXED32:
- skipRawBytes(4);
- return true;
- default:
- throw InvalidProtocolBufferException.invalidWireType();
- }
- }
+ public abstract boolean skipField(final int tag) throws IOException;
/**
- * Reads a single field and writes it to output in wire format,
- * given its tag value.
+ * Reads a single field and writes it to output in wire format, given its tag value.
*
- * @return {@code false} if the tag is an endgroup tag, in which case
- * nothing is skipped. Otherwise, returns {@code true}.
+ * @return {@code false} if the tag is an endgroup tag, in which case nothing is skipped.
+ * Otherwise, returns {@code true}.
+ * @deprecated use {@code UnknownFieldSet} or {@code UnknownFieldSetLite} to skip to an output
+ * stream.
*/
- public boolean skipField(final int tag, final CodedOutputStream output)
- throws IOException {
- switch (WireFormat.getTagWireType(tag)) {
- case WireFormat.WIRETYPE_VARINT: {
- long value = readInt64();
- output.writeRawVarint32(tag);
- output.writeUInt64NoTag(value);
- return true;
- }
- case WireFormat.WIRETYPE_FIXED64: {
- long value = readRawLittleEndian64();
- output.writeRawVarint32(tag);
- output.writeFixed64NoTag(value);
- return true;
- }
- case WireFormat.WIRETYPE_LENGTH_DELIMITED: {
- ByteString value = readBytes();
- output.writeRawVarint32(tag);
- output.writeBytesNoTag(value);
- return true;
- }
- case WireFormat.WIRETYPE_START_GROUP: {
- output.writeRawVarint32(tag);
- skipMessage(output);
- int endtag = WireFormat.makeTag(WireFormat.getTagFieldNumber(tag),
- WireFormat.WIRETYPE_END_GROUP);
- checkLastTagWas(endtag);
- output.writeRawVarint32(endtag);
- return true;
- }
- case WireFormat.WIRETYPE_END_GROUP: {
- return false;
- }
- case WireFormat.WIRETYPE_FIXED32: {
- int value = readRawLittleEndian32();
- output.writeRawVarint32(tag);
- output.writeFixed32NoTag(value);
- return true;
- }
- default:
- throw InvalidProtocolBufferException.invalidWireType();
- }
- }
-
- /**
- * 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;
- }
- }
- }
+ @Deprecated
+ public abstract boolean skipField(final int tag, final CodedOutputStream output)
+ throws IOException;
/**
- * Reads an entire message and writes it to output in wire format.
- * This will read either until EOF or until an endgroup tag,
+ * Reads and discards an entire message. This will read either until EOF or until an endgroup tag,
* whichever comes first.
*/
- public void skipMessage(CodedOutputStream output) throws IOException {
- while (true) {
- final int tag = readTag();
- if (tag == 0 || !skipField(tag, output)) {
- return;
- }
- }
- }
+ public abstract void skipMessage() throws IOException;
/**
- * Collects the bytes skipped and returns the data in a ByteBuffer.
+ * Reads an entire message and writes it to output in wire format. This will read either until EOF
+ * or until an endgroup tag, whichever comes first.
*/
- private class SkippedDataSink implements RefillCallback {
- private int lastPos = bufferPos;
- private ByteArrayOutputStream byteArrayStream;
-
- @Override
- public void onRefill() {
- if (byteArrayStream == null) {
- byteArrayStream = new ByteArrayOutputStream();
- }
- byteArrayStream.write(buffer, lastPos, bufferPos - lastPos);
- lastPos = 0;
- }
-
- /**
- * Gets skipped data in a ByteBuffer. This method should only be
- * called once.
- */
- ByteBuffer getSkippedData() {
- if (byteArrayStream == null) {
- return ByteBuffer.wrap(buffer, lastPos, bufferPos - lastPos);
- } else {
- byteArrayStream.write(buffer, lastPos, bufferPos);
- return ByteBuffer.wrap(byteArrayStream.toByteArray());
- }
- }
- }
+ public abstract void skipMessage(CodedOutputStream output) throws IOException;
// -----------------------------------------------------------------
/** Read a {@code double} field value from the stream. */
- public double readDouble() throws IOException {
- return Double.longBitsToDouble(readRawLittleEndian64());
- }
+ public abstract double readDouble() throws IOException;
/** Read a {@code float} field value from the stream. */
- public float readFloat() throws IOException {
- return Float.intBitsToFloat(readRawLittleEndian32());
- }
+ public abstract float readFloat() throws IOException;
/** Read a {@code uint64} field value from the stream. */
- public long readUInt64() throws IOException {
- return readRawVarint64();
- }
+ public abstract long readUInt64() throws IOException;
/** Read an {@code int64} field value from the stream. */
- public long readInt64() throws IOException {
- return readRawVarint64();
- }
+ public abstract long readInt64() throws IOException;
/** Read an {@code int32} field value from the stream. */
- public int readInt32() throws IOException {
- return readRawVarint32();
- }
+ public abstract int readInt32() throws IOException;
/** Read a {@code fixed64} field value from the stream. */
- public long readFixed64() throws IOException {
- return readRawLittleEndian64();
- }
+ public abstract long readFixed64() throws IOException;
/** Read a {@code fixed32} field value from the stream. */
- public int readFixed32() throws IOException {
- return readRawLittleEndian32();
- }
+ public abstract int readFixed32() throws IOException;
/** Read a {@code bool} field value from the stream. */
- public boolean readBool() throws IOException {
- return readRawVarint64() != 0;
- }
+ public abstract boolean readBool() throws IOException;
/**
- * Read a {@code string} field value from the stream.
- * If the stream contains malformed UTF-8,
+ * Read a {@code string} field value from the stream. If the stream contains malformed UTF-8,
* replace the offending bytes with the standard UTF-8 replacement character.
*/
- 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, Internal.UTF_8);
- bufferPos += size;
- return result;
- } else if (size == 0) {
- return "";
- } else if (size <= bufferSize) {
- refillBuffer(size);
- String result = new String(buffer, bufferPos, size, Internal.UTF_8);
- bufferPos += size;
- return result;
- } else {
- // Slow path: Build a byte array first then copy it.
- return new String(readRawBytesSlowPath(size), Internal.UTF_8);
- }
- }
+ public abstract String readString() throws IOException;
/**
- * Read a {@code string} field value from the stream.
- * If the stream contains malformed UTF-8,
+ * Read a {@code string} field value from the stream. If the stream contains malformed UTF-8,
* throw exception {@link InvalidProtocolBufferException}.
*/
- public String readStringRequireUtf8() throws IOException {
- final int size = readRawVarint32();
- final byte[] bytes;
- final int oldPos = bufferPos;
- final int pos;
- if (size <= (bufferSize - oldPos) && size > 0) {
- // Fast path: We already have the bytes in a contiguous buffer, so
- // just copy directly from it.
- bytes = buffer;
- bufferPos = oldPos + size;
- pos = oldPos;
- } else if (size == 0) {
- return "";
- } else if (size <= bufferSize) {
- refillBuffer(size);
- bytes = buffer;
- pos = 0;
- bufferPos = pos + size;
- } else {
- // Slow path: Build a byte array first then copy it.
- bytes = readRawBytesSlowPath(size);
- pos = 0;
- }
- // TODO(martinrb): We could save a pass by validating while decoding.
- if (!Utf8.isValidUtf8(bytes, pos, pos + size)) {
- throw InvalidProtocolBufferException.invalidUtf8();
- }
- return new String(bytes, pos, size, Internal.UTF_8);
- }
+ public abstract String readStringRequireUtf8() throws IOException;
/** Read a {@code group} field value from the stream. */
- public void readGroup(final int fieldNumber,
- final MessageLite.Builder builder,
- final ExtensionRegistryLite extensionRegistry)
- throws IOException {
- if (recursionDepth >= recursionLimit) {
- throw InvalidProtocolBufferException.recursionLimitExceeded();
- }
- ++recursionDepth;
- builder.mergeFrom(this, extensionRegistry);
- checkLastTagWas(
- WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
- --recursionDepth;
- }
+ public abstract void readGroup(
+ final int fieldNumber,
+ final MessageLite.Builder builder,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException;
/** Read a {@code group} field value from the stream. */
- public <T extends MessageLite> T readGroup(
- final int fieldNumber,
- final Parser<T> parser,
- final ExtensionRegistryLite extensionRegistry)
- throws IOException {
- if (recursionDepth >= recursionLimit) {
- throw InvalidProtocolBufferException.recursionLimitExceeded();
- }
- ++recursionDepth;
- T result = parser.parsePartialFrom(this, extensionRegistry);
- checkLastTagWas(
- WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
- --recursionDepth;
- return result;
- }
+ public abstract <T extends MessageLite> T readGroup(
+ final int fieldNumber, final Parser<T> parser, final ExtensionRegistryLite extensionRegistry)
+ throws IOException;
/**
- * Reads a {@code group} field value from the stream and merges it into the
- * given {@link UnknownFieldSet}.
+ * Reads a {@code group} field value from the stream and merges it into the given {@link
+ * UnknownFieldSet}.
*
- * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so
- * you can just call {@link #readGroup}.
+ * @deprecated UnknownFieldSet.Builder now implements MessageLite.Builder, so you can just call
+ * {@link #readGroup}.
*/
@Deprecated
- public void readUnknownGroup(final int fieldNumber,
- final MessageLite.Builder builder)
- throws IOException {
- // We know that UnknownFieldSet will ignore any ExtensionRegistry so it
- // is safe to pass null here. (We can't call
- // ExtensionRegistry.getEmptyRegistry() because that would make this
- // class depend on ExtensionRegistry, which is not part of the lite
- // library.)
- readGroup(fieldNumber, builder, null);
- }
+ public abstract void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder)
+ throws IOException;
/** Read an embedded message field value from the stream. */
- public void readMessage(final MessageLite.Builder builder,
- final ExtensionRegistryLite extensionRegistry)
- throws IOException {
- final int length = readRawVarint32();
- if (recursionDepth >= recursionLimit) {
- throw InvalidProtocolBufferException.recursionLimitExceeded();
- }
- final int oldLimit = pushLimit(length);
- ++recursionDepth;
- builder.mergeFrom(this, extensionRegistry);
- checkLastTagWas(0);
- --recursionDepth;
- popLimit(oldLimit);
- }
+ public abstract void readMessage(
+ final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry)
+ throws IOException;
/** Read an embedded message field value from the stream. */
- public <T extends MessageLite> T readMessage(
- final Parser<T> parser,
- final ExtensionRegistryLite extensionRegistry)
- throws IOException {
- int length = readRawVarint32();
- if (recursionDepth >= recursionLimit) {
- throw InvalidProtocolBufferException.recursionLimitExceeded();
- }
- final int oldLimit = pushLimit(length);
- ++recursionDepth;
- T result = parser.parsePartialFrom(this, extensionRegistry);
- checkLastTagWas(0);
- --recursionDepth;
- popLimit(oldLimit);
- return result;
- }
+ public abstract <T extends MessageLite> T readMessage(
+ final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException;
/** Read a {@code bytes} field value from the stream. */
- public ByteString 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 ByteString result = bufferIsImmutable && enableAliasing
- ? ByteString.wrap(buffer, bufferPos, size)
- : ByteString.copyFrom(buffer, bufferPos, size);
- bufferPos += size;
- return result;
- } else if (size == 0) {
- return ByteString.EMPTY;
- } else {
- // Slow path: Build a byte array first then copy it.
- return ByteString.wrap(readRawBytesSlowPath(size));
- }
- }
+ public abstract ByteString readBytes() throws IOException;
/** Read a {@code bytes} field value from the stream. */
- public byte[] readByteArray() 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 =
- Arrays.copyOfRange(buffer, bufferPos, bufferPos + size);
- bufferPos += size;
- return result;
- } else {
- // Slow path: Build a byte array first then copy it.
- return readRawBytesSlowPath(size);
- }
- }
+ public abstract byte[] readByteArray() throws IOException;
/** Read a {@code bytes} field value from the stream. */
- public ByteBuffer readByteBuffer() throws IOException {
- final int size = readRawVarint32();
- if (size <= (bufferSize - bufferPos) && size > 0) {
- // Fast path: We already have the bytes in a contiguous buffer.
- // When aliasing is enabled, we can return a ByteBuffer pointing directly
- // into the underlying byte array without copy if the CodedInputStream is
- // constructed from a byte array. If aliasing is disabled or the input is
- // from an InputStream or ByteString, we have to make a copy of the bytes.
- ByteBuffer result = input == null && !bufferIsImmutable && enableAliasing
- ? ByteBuffer.wrap(buffer, bufferPos, size).slice()
- : ByteBuffer.wrap(Arrays.copyOfRange(
- buffer, bufferPos, bufferPos + size));
- bufferPos += size;
- return result;
- } else if (size == 0) {
- return Internal.EMPTY_BYTE_BUFFER;
- } else {
- // Slow path: Build a byte array first then copy it.
- return ByteBuffer.wrap(readRawBytesSlowPath(size));
- }
- }
+ public abstract ByteBuffer readByteBuffer() throws IOException;
/** Read a {@code uint32} field value from the stream. */
- public int readUInt32() throws IOException {
- return readRawVarint32();
- }
+ public abstract int readUInt32() throws IOException;
/**
- * Read an enum field value from the stream. Caller is responsible
- * for converting the numeric value to an actual enum.
+ * 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();
- }
+ public abstract int readEnum() throws IOException;
/** Read an {@code sfixed32} field value from the stream. */
- public int readSFixed32() throws IOException {
- return readRawLittleEndian32();
- }
+ public abstract int readSFixed32() throws IOException;
/** Read an {@code sfixed64} field value from the stream. */
- public long readSFixed64() throws IOException {
- return readRawLittleEndian64();
- }
+ public abstract long readSFixed64() throws IOException;
/** Read an {@code sint32} field value from the stream. */
- public int readSInt32() throws IOException {
- return decodeZigZag32(readRawVarint32());
- }
+ public abstract int readSInt32() throws IOException;
/** Read an {@code sint64} field value from the stream. */
- public long readSInt64() throws IOException {
- return decodeZigZag64(readRawVarint64());
- }
+ public abstract long readSInt64() throws IOException;
// =================================================================
+ /** Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits. */
+ public abstract int readRawVarint32() throws IOException;
+
+ /** Read a raw Varint from the stream. */
+ public abstract long readRawVarint64() throws IOException;
+
+ /** Variant of readRawVarint64 for when uncomfortably close to the limit. */
+ /* Visible for testing */
+ abstract long readRawVarint64SlowPath() throws IOException;
+
+ /** Read a 32-bit little-endian integer from the stream. */
+ public abstract int readRawLittleEndian32() throws IOException;
+
+ /** Read a 64-bit little-endian integer from the stream. */
+ public abstract long readRawLittleEndian64() throws IOException;
+
+ // -----------------------------------------------------------------
+
/**
- * Read a raw Varint from the stream. If larger than 32 bits, discard the
- * upper bits.
+ * Enables {@link ByteString} aliasing of the underlying buffer, trading off on buffer pinning for
+ * data copies. Only valid for buffer-backed streams.
*/
- public int readRawVarint32() throws IOException {
- // See implementation notes for readRawVarint64
- fastpath: {
- int pos = bufferPos;
-
- if (bufferSize == pos) {
- break fastpath;
- }
+ public abstract void enableAliasing(boolean enabled);
- final byte[] buffer = this.buffer;
- int x;
- if ((x = buffer[pos++]) >= 0) {
- bufferPos = pos;
- return x;
- } else if (bufferSize - pos < 9) {
- break fastpath;
- } else if ((x ^= (buffer[pos++] << 7)) < 0) {
- x ^= (~0 << 7);
- } else if ((x ^= (buffer[pos++] << 14)) >= 0) {
- x ^= (~0 << 7) ^ (~0 << 14);
- } else if ((x ^= (buffer[pos++] << 21)) < 0) {
- x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21);
- } else {
- int y = buffer[pos++];
- x ^= y << 28;
- x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28);
- if (y < 0 &&
- buffer[pos++] < 0 &&
- buffer[pos++] < 0 &&
- buffer[pos++] < 0 &&
- buffer[pos++] < 0 &&
- buffer[pos++] < 0) {
- break fastpath; // Will throw malformedVarint()
- }
- }
- bufferPos = pos;
- return x;
+ /**
+ * 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 final int setRecursionLimit(final int limit) {
+ if (limit < 0) {
+ throw new IllegalArgumentException("Recursion limit cannot be negative: " + limit);
}
- return (int) readRawVarint64SlowPath();
+ final int oldLimit = recursionLimit;
+ recursionLimit = limit;
+ return oldLimit;
}
- private void skipRawVarint() throws IOException {
- if (bufferSize - bufferPos >= 10) {
- final byte[] buffer = this.buffer;
- int pos = bufferPos;
- for (int i = 0; i < 10; i++) {
- if (buffer[pos++] >= 0) {
- bufferPos = pos;
- return;
- }
- }
+ /**
+ * Only valid for {@link InputStream}-backed streams.
+ *
+ * <p>Set the maximum message size. In order to prevent malicious messages from exhausting memory
+ * or causing integer overflows, {@code CodedInputStream} limits how large a message may be. The
+ * default limit is 64MB. You should set this limit as small as you can without harming your app's
+ * functionality. Note that size limits only apply when reading from an {@code InputStream}, not
+ * when constructed around a raw byte array (nor with {@link ByteString#newCodedInput}).
+ *
+ * <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 final int setSizeLimit(final int limit) {
+ if (limit < 0) {
+ throw new IllegalArgumentException("Size limit cannot be negative: " + limit);
}
- skipRawVarintSlowPath();
+ final int oldLimit = sizeLimit;
+ sizeLimit = limit;
+ return oldLimit;
}
- private void skipRawVarintSlowPath() throws IOException {
- for (int i = 0; i < 10; i++) {
- if (readRawByte() >= 0) {
- return;
- }
- }
- throw InvalidProtocolBufferException.malformedVarint();
+ /**
+ * Resets the current size counter to zero (see {@link #setSizeLimit(int)}). Only valid for {@link
+ * InputStream}-backed streams.
+ */
+ public abstract void resetSizeCounter();
+
+ /**
+ * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This is called when
+ * descending into a length-delimited embedded message.
+ *
+ * <p>Note that {@code pushLimit()} does NOT affect how many bytes the {@code CodedInputStream}
+ * reads from an underlying {@code InputStream} when refreshing its buffer. If you need to prevent
+ * reading past a certain point in the underlying {@code InputStream} (e.g. because you expect it
+ * to contain more data after the end of the message which you need to handle differently) then
+ * you must place a wrapper around your {@code InputStream} which limits the amount of data that
+ * can be read from it.
+ *
+ * @return the old limit.
+ */
+ public abstract int pushLimit(int byteLimit) throws InvalidProtocolBufferException;
+
+ /**
+ * Discards the current limit, returning to the previous limit.
+ *
+ * @param oldLimit The old limit, as returned by {@code pushLimit}.
+ */
+ public abstract void popLimit(final int oldLimit);
+
+ /**
+ * Returns the number of bytes to be read before the current limit. If no limit is set, returns
+ * -1.
+ */
+ public abstract int getBytesUntilLimit();
+
+ /**
+ * 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 abstract boolean isAtEnd() throws IOException;
+
+ /**
+ * The total bytes read up to the current position. Calling {@link #resetSizeCounter()} resets
+ * this value to zero.
+ */
+ public abstract int getTotalBytesRead();
+
+ /**
+ * Read one byte from the input.
+ *
+ * @throws InvalidProtocolBufferException The end of the stream or the current limit was reached.
+ */
+ public abstract byte readRawByte() throws IOException;
+
+ /**
+ * Read a fixed size of bytes from the input.
+ *
+ * @throws InvalidProtocolBufferException The end of the stream or the current limit was reached.
+ */
+ public abstract byte[] readRawBytes(final int size) throws IOException;
+
+ /**
+ * Reads and discards {@code size} bytes.
+ *
+ * @throws InvalidProtocolBufferException The end of the stream or the current limit was reached.
+ */
+ public abstract void skipRawBytes(final int size) throws IOException;
+
+ /**
+ * 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);
}
/**
- * Reads a varint from the input one byte at a time, so that it does not
- * read any bytes after the end of the varint. If you simply wrapped the
- * stream in a CodedInputStream and used {@link #readRawVarint32(InputStream)}
- * then you would probably end up reading past the end of the varint since
- * CodedInputStream buffers its input.
+ * 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.
*/
- static int readRawVarint32(final InputStream input) throws IOException {
- final int firstByte = input.read();
- if (firstByte == -1) {
- throw InvalidProtocolBufferException.truncatedMessage();
- }
- return readRawVarint32(firstByte, input);
+ public static long decodeZigZag64(final long n) {
+ return (n >>> 1) ^ -(n & 1);
}
/**
- * Like {@link #readRawVarint32(InputStream)}, but expects that the caller
- * has already read one byte. This allows the caller to determine if EOF
- * has been reached before attempting to read.
+ * Like {@link #readRawVarint32(InputStream)}, but expects that the caller has already read one
+ * byte. This allows the caller to determine if EOF has been reached before attempting to read.
*/
- public static int readRawVarint32(
- final int firstByte, final InputStream input) throws IOException {
+ public static int readRawVarint32(final int firstByte, final InputStream input)
+ throws IOException {
if ((firstByte & 0x80) == 0) {
return firstByte;
}
@@ -713,590 +500,2396 @@ public final class CodedInputStream {
throw InvalidProtocolBufferException.malformedVarint();
}
- /** Read a raw Varint from the stream. */
- public long readRawVarint64() throws IOException {
- // Implementation notes:
- //
- // Optimized for one-byte values, expected to be common.
- // The particular code below was selected from various candidates
- // empirically, by winning VarintBenchmark.
- //
- // Sign extension of (signed) Java bytes is usually a nuisance, but
- // we exploit it here to more easily obtain the sign of bytes read.
- // Instead of cleaning up the sign extension bits by masking eagerly,
- // we delay until we find the final (positive) byte, when we clear all
- // accumulated bits with one xor. We depend on javac to constant fold.
- fastpath: {
- int pos = bufferPos;
-
- if (bufferSize == pos) {
- break fastpath;
+ /**
+ * Reads a varint from the input one byte at a time, so that it does not read any bytes after the
+ * end of the varint. If you simply wrapped the stream in a CodedInputStream and used {@link
+ * #readRawVarint32(InputStream)} then you would probably end up reading past the end of the
+ * varint since CodedInputStream buffers its input.
+ */
+ static int readRawVarint32(final InputStream input) throws IOException {
+ final int firstByte = input.read();
+ if (firstByte == -1) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ return readRawVarint32(firstByte, input);
+ }
+
+ /** A {@link CodedInputStream} implementation that uses a backing array as the input. */
+ private static final class ArrayDecoder extends CodedInputStream {
+ private final byte[] buffer;
+ private final boolean immutable;
+ private int limit;
+ private int bufferSizeAfterLimit;
+ private int pos;
+ private int startPos;
+ private int lastTag;
+ private boolean enableAliasing;
+
+ /** The absolute position of the end of the current message. */
+ private int currentLimit = Integer.MAX_VALUE;
+
+ private ArrayDecoder(final byte[] buffer, final int offset, final int len, boolean immutable) {
+ this.buffer = buffer;
+ limit = offset + len;
+ pos = offset;
+ startPos = pos;
+ this.immutable = immutable;
+ }
+
+ @Override
+ public int readTag() throws IOException {
+ if (isAtEnd()) {
+ lastTag = 0;
+ return 0;
}
- final byte[] buffer = this.buffer;
- long x;
- int y;
- if ((y = buffer[pos++]) >= 0) {
- bufferPos = pos;
- return y;
- } else if (bufferSize - pos < 9) {
- break fastpath;
- } else if ((y ^= (buffer[pos++] << 7)) < 0) {
- x = y ^ (~0 << 7);
- } else if ((y ^= (buffer[pos++] << 14)) >= 0) {
- x = y ^ ((~0 << 7) ^ (~0 << 14));
- } else if ((y ^= (buffer[pos++] << 21)) < 0) {
- x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21));
- } else if ((x = ((long) y) ^ ((long) buffer[pos++] << 28)) >= 0L) {
- x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28);
- } else if ((x ^= ((long) buffer[pos++] << 35)) < 0L) {
- x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35);
- } else if ((x ^= ((long) buffer[pos++] << 42)) >= 0L) {
- x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42);
- } else if ((x ^= ((long) buffer[pos++] << 49)) < 0L) {
- x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42)
- ^ (~0L << 49);
- } else {
- x ^= ((long) buffer[pos++] << 56);
- x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42)
- ^ (~0L << 49) ^ (~0L << 56);
- if (x < 0L) {
- if (buffer[pos++] < 0L) {
- break fastpath; // Will throw malformedVarint()
+ lastTag = readRawVarint32();
+ if (WireFormat.getTagFieldNumber(lastTag) == 0) {
+ // If we actually read zero (or any tag number corresponding to field
+ // number zero), that's not a valid tag.
+ throw InvalidProtocolBufferException.invalidTag();
+ }
+ return lastTag;
+ }
+
+ @Override
+ public void checkLastTagWas(final int value) throws InvalidProtocolBufferException {
+ if (lastTag != value) {
+ throw InvalidProtocolBufferException.invalidEndTag();
+ }
+ }
+
+ @Override
+ public int getLastTag() {
+ return lastTag;
+ }
+
+ @Override
+ public boolean skipField(final int tag) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ skipRawVarint();
+ return true;
+ case WireFormat.WIRETYPE_FIXED64:
+ skipRawBytes(FIXED_64_SIZE);
+ return true;
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ skipRawBytes(readRawVarint32());
+ return true;
+ case WireFormat.WIRETYPE_START_GROUP:
+ skipMessage();
+ checkLastTagWas(
+ WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP));
+ return true;
+ case WireFormat.WIRETYPE_END_GROUP:
+ return false;
+ case WireFormat.WIRETYPE_FIXED32:
+ skipRawBytes(FIXED_32_SIZE);
+ return true;
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public boolean skipField(final int tag, final CodedOutputStream output) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ {
+ long value = readInt64();
+ output.writeRawVarint32(tag);
+ output.writeUInt64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_FIXED64:
+ {
+ long value = readRawLittleEndian64();
+ output.writeRawVarint32(tag);
+ output.writeFixed64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ {
+ ByteString value = readBytes();
+ output.writeRawVarint32(tag);
+ output.writeBytesNoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_START_GROUP:
+ {
+ output.writeRawVarint32(tag);
+ skipMessage(output);
+ int endtag =
+ WireFormat.makeTag(
+ WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
+ checkLastTagWas(endtag);
+ output.writeRawVarint32(endtag);
+ return true;
}
+ case WireFormat.WIRETYPE_END_GROUP:
+ {
+ return false;
+ }
+ case WireFormat.WIRETYPE_FIXED32:
+ {
+ int value = readRawLittleEndian32();
+ output.writeRawVarint32(tag);
+ output.writeFixed32NoTag(value);
+ return true;
+ }
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public void skipMessage() throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag)) {
+ return;
}
}
- bufferPos = pos;
- return x;
}
- return readRawVarint64SlowPath();
- }
- /** Variant of readRawVarint64 for when uncomfortably close to the limit. */
- /* Visible for testing */
- long readRawVarint64SlowPath() throws IOException {
- long result = 0;
- for (int shift = 0; shift < 64; shift += 7) {
- final byte b = readRawByte();
- result |= (long) (b & 0x7F) << shift;
- if ((b & 0x80) == 0) {
- return result;
+ @Override
+ public void skipMessage(CodedOutputStream output) throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag, output)) {
+ return;
+ }
}
}
- throw InvalidProtocolBufferException.malformedVarint();
- }
- /** Read a 32-bit little-endian integer from the stream. */
- public int readRawLittleEndian32() throws IOException {
- int pos = bufferPos;
- // hand-inlined ensureAvailable(4);
- if (bufferSize - pos < 4) {
- refillBuffer(4);
- pos = bufferPos;
+ // -----------------------------------------------------------------
+
+ @Override
+ public double readDouble() throws IOException {
+ return Double.longBitsToDouble(readRawLittleEndian64());
}
- final byte[] buffer = this.buffer;
- bufferPos = pos + 4;
- return (((buffer[pos] & 0xff)) |
- ((buffer[pos + 1] & 0xff) << 8) |
- ((buffer[pos + 2] & 0xff) << 16) |
- ((buffer[pos + 3] & 0xff) << 24));
- }
+ @Override
+ public float readFloat() throws IOException {
+ return Float.intBitsToFloat(readRawLittleEndian32());
+ }
- /** Read a 64-bit little-endian integer from the stream. */
- public long readRawLittleEndian64() throws IOException {
- int pos = bufferPos;
-
- // hand-inlined ensureAvailable(8);
- if (bufferSize - pos < 8) {
- refillBuffer(8);
- pos = bufferPos;
- }
-
- final byte[] buffer = this.buffer;
- bufferPos = pos + 8;
- return ((((long) buffer[pos] & 0xffL)) |
- (((long) buffer[pos + 1] & 0xffL) << 8) |
- (((long) buffer[pos + 2] & 0xffL) << 16) |
- (((long) buffer[pos + 3] & 0xffL) << 24) |
- (((long) buffer[pos + 4] & 0xffL) << 32) |
- (((long) buffer[pos + 5] & 0xffL) << 40) |
- (((long) buffer[pos + 6] & 0xffL) << 48) |
- (((long) buffer[pos + 7] & 0xffL) << 56));
- }
+ @Override
+ public long readUInt64() throws IOException {
+ return readRawVarint64();
+ }
- /**
- * 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);
- }
+ @Override
+ public long readInt64() throws IOException {
+ return readRawVarint64();
+ }
- /**
- * 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);
- }
+ @Override
+ public int readInt32() throws IOException {
+ return readRawVarint32();
+ }
- // -----------------------------------------------------------------
+ @Override
+ public long readFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
- private final byte[] buffer;
- private final boolean bufferIsImmutable;
- private int bufferSize;
- private int bufferSizeAfterLimit;
- private int bufferPos;
- private final InputStream input;
- private int lastTag;
- private boolean enableAliasing = false;
+ @Override
+ public int readFixed32() throws IOException {
+ return readRawLittleEndian32();
+ }
- /**
- * The total number of bytes read before the current buffer. The total
- * bytes read up to the current position can be computed as
- * {@code totalBytesRetired + bufferPos}. This value may be negative if
- * reading started in the middle of the current buffer (e.g. if the
- * constructor that takes a byte array and an offset was used).
- */
- private int totalBytesRetired;
+ @Override
+ public boolean readBool() throws IOException {
+ return readRawVarint64() != 0;
+ }
- /** The absolute position of the end of the current message. */
- private int currentLimit = Integer.MAX_VALUE;
+ @Override
+ public String readString() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= (limit - pos)) {
+ // Fast path: We already have the bytes in a contiguous buffer, so
+ // just copy directly from it.
+ final String result = new String(buffer, pos, size, UTF_8);
+ pos += size;
+ return result;
+ }
- /** See setRecursionLimit() */
- private int recursionDepth;
- private int recursionLimit = DEFAULT_RECURSION_LIMIT;
+ if (size == 0) {
+ return "";
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
- /** See setSizeLimit() */
- private int sizeLimit = DEFAULT_SIZE_LIMIT;
+ @Override
+ 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();
+ }
+ final int tempPos = pos;
+ pos += size;
+ return new String(buffer, tempPos, size, UTF_8);
+ }
- private static final int DEFAULT_RECURSION_LIMIT = 100;
- private static final int DEFAULT_SIZE_LIMIT = 64 << 20; // 64MB
- private static final int BUFFER_SIZE = 4096;
-
- private CodedInputStream(
- final byte[] buffer, final int off, final int len, boolean bufferIsImmutable) {
- this.buffer = buffer;
- bufferSize = off + len;
- bufferPos = off;
- totalBytesRetired = -off;
- input = null;
- this.bufferIsImmutable = bufferIsImmutable;
- }
+ if (size == 0) {
+ return "";
+ }
+ if (size <= 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
- private CodedInputStream(final InputStream input, int bufferSize) {
- buffer = new byte[bufferSize];
- bufferSize = 0;
- bufferPos = 0;
- totalBytesRetired = 0;
- this.input = input;
- bufferIsImmutable = false;
- }
+ @Override
+ public void readGroup(
+ final int fieldNumber,
+ final MessageLite.Builder builder,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ }
- public void enableAliasing(boolean enabled) {
- this.enableAliasing = enabled;
- }
- /**
- * 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);
+ @Override
+ public <T extends MessageLite> T readGroup(
+ final int fieldNumber,
+ final Parser<T> parser,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ return result;
}
- 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 (nor with
- * {@link ByteString#newCodedInput}).
- * <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);
+ @Deprecated
+ @Override
+ public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder)
+ throws IOException {
+ readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry());
}
- final int oldLimit = sizeLimit;
- sizeLimit = limit;
- return oldLimit;
- }
- /**
- * Resets the current size counter to zero (see {@link #setSizeLimit(int)}).
- */
- public void resetSizeCounter() {
- totalBytesRetired = -bufferPos;
- }
+ @Override
+ public void readMessage(
+ final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ final int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ }
- /**
- * Sets {@code currentLimit} to (current position) + {@code byteLimit}. This
- * is called when descending into a length-delimited embedded message.
- *
- * <p>Note that {@code pushLimit()} does NOT affect how many bytes the
- * {@code CodedInputStream} reads from an underlying {@code InputStream} when
- * refreshing its buffer. If you need to prevent reading past a certain
- * point in the underlying {@code InputStream} (e.g. because you expect it to
- * contain more data after the end of the message which you need to handle
- * differently) then you must place a wrapper around your {@code InputStream}
- * which limits the amount of data that can be read from it.
- *
- * @return the old limit.
- */
- public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
- if (byteLimit < 0) {
- throw InvalidProtocolBufferException.negativeSize();
+
+ @Override
+ public <T extends MessageLite> T readMessage(
+ final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException {
+ int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ return result;
+ }
+
+ @Override
+ public ByteString readBytes() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= (limit - pos)) {
+ // Fast path: We already have the bytes in a contiguous buffer, so
+ // just copy directly from it.
+ final ByteString result =
+ immutable && enableAliasing
+ ? ByteString.wrap(buffer, pos, size)
+ : ByteString.copyFrom(buffer, pos, size);
+ pos += size;
+ return result;
+ }
+ if (size == 0) {
+ return ByteString.EMPTY;
+ }
+ // Slow path: Build a byte array first then copy it.
+ return ByteString.wrap(readRawBytes(size));
+ }
+
+ @Override
+ public byte[] readByteArray() throws IOException {
+ final int size = readRawVarint32();
+ return readRawBytes(size);
}
- byteLimit += totalBytesRetired + bufferPos;
- final int oldLimit = currentLimit;
- if (byteLimit > oldLimit) {
+
+ @Override
+ public ByteBuffer readByteBuffer() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= (limit - pos)) {
+ // Fast path: We already have the bytes in a contiguous buffer.
+ // When aliasing is enabled, we can return a ByteBuffer pointing directly
+ // into the underlying byte array without copy if the CodedInputStream is
+ // constructed from a byte array. If aliasing is disabled or the input is
+ // from an InputStream or ByteString, we have to make a copy of the bytes.
+ ByteBuffer result =
+ !immutable && enableAliasing
+ ? ByteBuffer.wrap(buffer, pos, size).slice()
+ : ByteBuffer.wrap(Arrays.copyOfRange(buffer, pos, pos + size));
+ pos += size;
+ // TODO(nathanmittler): Investigate making the ByteBuffer be made read-only
+ return result;
+ }
+
+ if (size == 0) {
+ return EMPTY_BYTE_BUFFER;
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
throw InvalidProtocolBufferException.truncatedMessage();
}
- currentLimit = byteLimit;
- recomputeBufferSizeAfterLimit();
+ @Override
+ public int readUInt32() throws IOException {
+ return readRawVarint32();
+ }
- return oldLimit;
- }
+ @Override
+ public int readEnum() throws IOException {
+ return readRawVarint32();
+ }
- private void recomputeBufferSizeAfterLimit() {
- bufferSize += bufferSizeAfterLimit;
- final int bufferEnd = totalBytesRetired + bufferSize;
- if (bufferEnd > currentLimit) {
- // Limit is in current buffer.
- bufferSizeAfterLimit = bufferEnd - currentLimit;
- bufferSize -= bufferSizeAfterLimit;
- } else {
- bufferSizeAfterLimit = 0;
+ @Override
+ public int readSFixed32() throws IOException {
+ return readRawLittleEndian32();
}
- }
- /**
- * 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();
- }
+ @Override
+ public long readSFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
- /**
- * 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;
+ @Override
+ public int readSInt32() throws IOException {
+ return decodeZigZag32(readRawVarint32());
}
- final int currentAbsolutePosition = totalBytesRetired + bufferPos;
- return currentLimit - currentAbsolutePosition;
- }
+ @Override
+ public long readSInt64() throws IOException {
+ return decodeZigZag64(readRawVarint64());
+ }
- /**
- * 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() throws IOException {
- return bufferPos == bufferSize && !tryRefillBuffer(1);
- }
+ // =================================================================
- /**
- * The total bytes read up to the current position. Calling
- * {@link #resetSizeCounter()} resets this value to zero.
- */
- public int getTotalBytesRead() {
- return totalBytesRetired + bufferPos;
- }
+ @Override
+ public int readRawVarint32() throws IOException {
+ // See implementation notes for readRawVarint64
+ fastpath:
+ {
+ int tempPos = pos;
+
+ if (limit == tempPos) {
+ break fastpath;
+ }
- private interface RefillCallback {
- void onRefill();
- }
+ final byte[] buffer = this.buffer;
+ int x;
+ if ((x = buffer[tempPos++]) >= 0) {
+ pos = tempPos;
+ return x;
+ } else if (limit - tempPos < 9) {
+ break fastpath;
+ } else if ((x ^= (buffer[tempPos++] << 7)) < 0) {
+ x ^= (~0 << 7);
+ } else if ((x ^= (buffer[tempPos++] << 14)) >= 0) {
+ x ^= (~0 << 7) ^ (~0 << 14);
+ } else if ((x ^= (buffer[tempPos++] << 21)) < 0) {
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21);
+ } else {
+ int y = buffer[tempPos++];
+ x ^= y << 28;
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28);
+ if (y < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ pos = tempPos;
+ return x;
+ }
+ return (int) readRawVarint64SlowPath();
+ }
- private RefillCallback refillCallback = null;
+ private void skipRawVarint() throws IOException {
+ if (limit - pos >= MAX_VARINT_SIZE) {
+ skipRawVarintFastPath();
+ } else {
+ skipRawVarintSlowPath();
+ }
+ }
- /**
- * Reads more bytes from the input, making at least {@code n} bytes available
- * in the buffer. Caller must ensure that the requested space is not yet
- * available, and that the requested space is less than BUFFER_SIZE.
- *
- * @throws InvalidProtocolBufferException The end of the stream or the current
- * limit was reached.
- */
- private void refillBuffer(int n) throws IOException {
- if (!tryRefillBuffer(n)) {
+ private void skipRawVarintFastPath() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (buffer[pos++] >= 0) {
+ return;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ private void skipRawVarintSlowPath() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (readRawByte() >= 0) {
+ return;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ @Override
+ public long readRawVarint64() throws IOException {
+ // Implementation notes:
+ //
+ // Optimized for one-byte values, expected to be common.
+ // The particular code below was selected from various candidates
+ // empirically, by winning VarintBenchmark.
+ //
+ // Sign extension of (signed) Java bytes is usually a nuisance, but
+ // we exploit it here to more easily obtain the sign of bytes read.
+ // Instead of cleaning up the sign extension bits by masking eagerly,
+ // we delay until we find the final (positive) byte, when we clear all
+ // accumulated bits with one xor. We depend on javac to constant fold.
+ fastpath:
+ {
+ int tempPos = pos;
+
+ if (limit == tempPos) {
+ break fastpath;
+ }
+
+ final byte[] buffer = this.buffer;
+ long x;
+ int y;
+ if ((y = buffer[tempPos++]) >= 0) {
+ pos = tempPos;
+ return y;
+ } else if (limit - tempPos < 9) {
+ break fastpath;
+ } else if ((y ^= (buffer[tempPos++] << 7)) < 0) {
+ x = y ^ (~0 << 7);
+ } else if ((y ^= (buffer[tempPos++] << 14)) >= 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14));
+ } else if ((y ^= (buffer[tempPos++] << 21)) < 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21));
+ } else if ((x = y ^ ((long) buffer[tempPos++] << 28)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28);
+ } else if ((x ^= ((long) buffer[tempPos++] << 35)) < 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35);
+ } else if ((x ^= ((long) buffer[tempPos++] << 42)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42);
+ } else if ((x ^= ((long) buffer[tempPos++] << 49)) < 0L) {
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49);
+ } else {
+ x ^= ((long) buffer[tempPos++] << 56);
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49)
+ ^ (~0L << 56);
+ if (x < 0L) {
+ if (buffer[tempPos++] < 0L) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ }
+ pos = tempPos;
+ return x;
+ }
+ return readRawVarint64SlowPath();
+ }
+
+ @Override
+ long readRawVarint64SlowPath() throws IOException {
+ long result = 0;
+ for (int shift = 0; shift < 64; shift += 7) {
+ final byte b = readRawByte();
+ result |= (long) (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ return result;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ @Override
+ public int readRawLittleEndian32() throws IOException {
+ int tempPos = pos;
+
+ if (limit - tempPos < FIXED_32_SIZE) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ final byte[] buffer = this.buffer;
+ pos = tempPos + FIXED_32_SIZE;
+ return (((buffer[tempPos] & 0xff))
+ | ((buffer[tempPos + 1] & 0xff) << 8)
+ | ((buffer[tempPos + 2] & 0xff) << 16)
+ | ((buffer[tempPos + 3] & 0xff) << 24));
+ }
+
+ @Override
+ public long readRawLittleEndian64() throws IOException {
+ int tempPos = pos;
+
+ if (limit - tempPos < FIXED_64_SIZE) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ final byte[] buffer = this.buffer;
+ pos = tempPos + FIXED_64_SIZE;
+ return (((buffer[tempPos] & 0xffL))
+ | ((buffer[tempPos + 1] & 0xffL) << 8)
+ | ((buffer[tempPos + 2] & 0xffL) << 16)
+ | ((buffer[tempPos + 3] & 0xffL) << 24)
+ | ((buffer[tempPos + 4] & 0xffL) << 32)
+ | ((buffer[tempPos + 5] & 0xffL) << 40)
+ | ((buffer[tempPos + 6] & 0xffL) << 48)
+ | ((buffer[tempPos + 7] & 0xffL) << 56));
+ }
+
+ @Override
+ public void enableAliasing(boolean enabled) {
+ this.enableAliasing = enabled;
+ }
+
+ @Override
+ public void resetSizeCounter() {
+ startPos = pos;
+ }
+
+ @Override
+ public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
+ if (byteLimit < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ byteLimit += getTotalBytesRead();
+ final int oldLimit = currentLimit;
+ if (byteLimit > oldLimit) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ currentLimit = byteLimit;
+
+ recomputeBufferSizeAfterLimit();
+
+ return oldLimit;
+ }
+
+ private void recomputeBufferSizeAfterLimit() {
+ limit += bufferSizeAfterLimit;
+ final int bufferEnd = limit - startPos;
+ if (bufferEnd > currentLimit) {
+ // Limit is in current buffer.
+ bufferSizeAfterLimit = bufferEnd - currentLimit;
+ limit -= bufferSizeAfterLimit;
+ } else {
+ bufferSizeAfterLimit = 0;
+ }
+ }
+
+ @Override
+ public void popLimit(final int oldLimit) {
+ currentLimit = oldLimit;
+ recomputeBufferSizeAfterLimit();
+ }
+
+ @Override
+ public int getBytesUntilLimit() {
+ if (currentLimit == Integer.MAX_VALUE) {
+ return -1;
+ }
+
+ return currentLimit - getTotalBytesRead();
+ }
+
+ @Override
+ public boolean isAtEnd() throws IOException {
+ return pos == limit;
+ }
+
+ @Override
+ public int getTotalBytesRead() {
+ return pos - startPos;
+ }
+
+ @Override
+ public byte readRawByte() throws IOException {
+ if (pos == limit) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ return buffer[pos++];
+ }
+
+ @Override
+ public byte[] readRawBytes(final int length) throws IOException {
+ if (length > 0 && length <= (limit - pos)) {
+ final int tempPos = pos;
+ pos += length;
+ return Arrays.copyOfRange(buffer, tempPos, pos);
+ }
+
+ if (length <= 0) {
+ if (length == 0) {
+ return Internal.EMPTY_BYTE_ARRAY;
+ } else {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public void skipRawBytes(final int length) throws IOException {
+ if (length >= 0 && length <= (limit - pos)) {
+ // We have all the bytes we need already.
+ pos += length;
+ return;
+ }
+
+ if (length < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
throw InvalidProtocolBufferException.truncatedMessage();
}
}
/**
- * Tries to read more bytes from the input, making at least {@code n} bytes
- * available in the buffer. Caller must ensure that the requested space is
- * not yet available, and that the requested space is less than BUFFER_SIZE.
- *
- * @return {@code true} if the bytes could be made available; {@code false}
- * if the end of the stream or the current limit was reached.
+ * A {@link CodedInputStream} implementation that uses a backing direct ByteBuffer as the input.
+ * Requires the use of {@code sun.misc.Unsafe} to perform fast reads on the buffer.
*/
- private boolean tryRefillBuffer(int n) throws IOException {
- if (bufferPos + n <= bufferSize) {
- throw new IllegalStateException(
- "refillBuffer() called when " + n +
- " bytes were already available in buffer");
+ private static final class UnsafeDirectNioDecoder extends CodedInputStream {
+ /** The direct buffer that is backing this stream. */
+ private final ByteBuffer buffer;
+
+ /**
+ * If {@code true}, indicates that the buffer is backing a {@link ByteString} and is therefore
+ * considered to be an immutable input source.
+ */
+ private final boolean immutable;
+
+ /** The unsafe address of the content of {@link #buffer}. */
+ private final long address;
+
+ /** The unsafe address of the current read limit of the buffer. */
+ private long limit;
+
+ /** The unsafe address of the current read position of the buffer. */
+ private long pos;
+
+ /** The unsafe address of the starting read position. */
+ private long startPos;
+
+ /** The amount of available data in the buffer beyond {@link #limit}. */
+ private int bufferSizeAfterLimit;
+
+ /** The last tag that was read from this stream. */
+ private int lastTag;
+
+ /**
+ * If {@code true}, indicates that calls to read {@link ByteString} or {@code byte[]}
+ * <strong>may</strong> return slices of the underlying buffer, rather than copies.
+ */
+ private boolean enableAliasing;
+
+ /** The absolute position of the end of the current message. */
+ private int currentLimit = Integer.MAX_VALUE;
+
+ static boolean isSupported() {
+ return UnsafeUtil.hasUnsafeByteBufferOperations();
}
- if (totalBytesRetired + bufferPos + n > currentLimit) {
- // Oops, we hit a limit.
- return false;
+ private UnsafeDirectNioDecoder(ByteBuffer buffer, boolean immutable) {
+ this.buffer = buffer;
+ address = UnsafeUtil.addressOffset(buffer);
+ limit = address + buffer.limit();
+ pos = address + buffer.position();
+ startPos = pos;
+ this.immutable = immutable;
}
- if (refillCallback != null) {
- refillCallback.onRefill();
+ @Override
+ public int readTag() throws IOException {
+ if (isAtEnd()) {
+ lastTag = 0;
+ return 0;
+ }
+
+ lastTag = readRawVarint32();
+ if (WireFormat.getTagFieldNumber(lastTag) == 0) {
+ // If we actually read zero (or any tag number corresponding to field
+ // number zero), that's not a valid tag.
+ throw InvalidProtocolBufferException.invalidTag();
+ }
+ return lastTag;
}
- if (input != null) {
- int pos = bufferPos;
- if (pos > 0) {
- if (bufferSize > pos) {
- System.arraycopy(buffer, pos, buffer, 0, bufferSize - pos);
- }
- totalBytesRetired += pos;
- bufferSize -= pos;
- bufferPos = 0;
+ @Override
+ public void checkLastTagWas(final int value) throws InvalidProtocolBufferException {
+ if (lastTag != value) {
+ throw InvalidProtocolBufferException.invalidEndTag();
}
+ }
- int bytesRead = input.read(buffer, bufferSize, buffer.length - bufferSize);
- if (bytesRead == 0 || bytesRead < -1 || bytesRead > buffer.length) {
- throw new IllegalStateException(
- "InputStream#read(byte[]) returned invalid result: " + bytesRead +
- "\nThe InputStream implementation is buggy.");
+ @Override
+ public int getLastTag() {
+ return lastTag;
+ }
+
+ @Override
+ public boolean skipField(final int tag) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ skipRawVarint();
+ return true;
+ case WireFormat.WIRETYPE_FIXED64:
+ skipRawBytes(FIXED_64_SIZE);
+ return true;
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ skipRawBytes(readRawVarint32());
+ return true;
+ case WireFormat.WIRETYPE_START_GROUP:
+ skipMessage();
+ checkLastTagWas(
+ WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP));
+ return true;
+ case WireFormat.WIRETYPE_END_GROUP:
+ return false;
+ case WireFormat.WIRETYPE_FIXED32:
+ skipRawBytes(FIXED_32_SIZE);
+ return true;
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
}
- if (bytesRead > 0) {
- bufferSize += bytesRead;
- // Integer-overflow-conscious check against sizeLimit
- if (totalBytesRetired + n - sizeLimit > 0) {
- throw InvalidProtocolBufferException.sizeLimitExceeded();
+ }
+
+ @Override
+ public boolean skipField(final int tag, final CodedOutputStream output) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ {
+ long value = readInt64();
+ output.writeRawVarint32(tag);
+ output.writeUInt64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_FIXED64:
+ {
+ long value = readRawLittleEndian64();
+ output.writeRawVarint32(tag);
+ output.writeFixed64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ {
+ ByteString value = readBytes();
+ output.writeRawVarint32(tag);
+ output.writeBytesNoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_START_GROUP:
+ {
+ output.writeRawVarint32(tag);
+ skipMessage(output);
+ int endtag =
+ WireFormat.makeTag(
+ WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
+ checkLastTagWas(endtag);
+ output.writeRawVarint32(endtag);
+ return true;
+ }
+ case WireFormat.WIRETYPE_END_GROUP:
+ {
+ return false;
+ }
+ case WireFormat.WIRETYPE_FIXED32:
+ {
+ int value = readRawLittleEndian32();
+ output.writeRawVarint32(tag);
+ output.writeFixed32NoTag(value);
+ return true;
+ }
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public void skipMessage() throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag)) {
+ return;
}
- recomputeBufferSizeAfterLimit();
- return (bufferSize >= n) ? true : tryRefillBuffer(n);
}
}
- return false;
- }
+ @Override
+ public void skipMessage(CodedOutputStream output) throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag, output)) {
+ return;
+ }
+ }
+ }
- /**
- * Read one byte from the input.
- *
- * @throws InvalidProtocolBufferException The end of the stream or the current
- * limit was reached.
- */
- public byte readRawByte() throws IOException {
- if (bufferPos == bufferSize) {
- refillBuffer(1);
+
+ // -----------------------------------------------------------------
+
+ @Override
+ public double readDouble() throws IOException {
+ return Double.longBitsToDouble(readRawLittleEndian64());
}
- return buffer[bufferPos++];
- }
- /**
- * Read a fixed size of bytes from the input.
- *
- * @throws InvalidProtocolBufferException The end of the stream or the current
- * limit was reached.
- */
- public byte[] readRawBytes(final int size) throws IOException {
- final int pos = bufferPos;
- if (size <= (bufferSize - pos) && size > 0) {
- bufferPos = pos + size;
- return Arrays.copyOfRange(buffer, pos, pos + size);
- } else {
- return readRawBytesSlowPath(size);
+ @Override
+ public float readFloat() throws IOException {
+ return Float.intBitsToFloat(readRawLittleEndian32());
}
- }
- /**
- * Exactly like readRawBytes, but caller must have already checked the fast
- * path: (size <= (bufferSize - pos) && size > 0)
- */
- private byte[] readRawBytesSlowPath(final int size) throws IOException {
- if (size <= 0) {
+ @Override
+ public long readUInt64() throws IOException {
+ return readRawVarint64();
+ }
+
+ @Override
+ public long readInt64() throws IOException {
+ return readRawVarint64();
+ }
+
+ @Override
+ public int readInt32() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public long readFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
+
+ @Override
+ public int readFixed32() throws IOException {
+ return readRawLittleEndian32();
+ }
+
+ @Override
+ public boolean readBool() throws IOException {
+ return readRawVarint64() != 0;
+ }
+
+ @Override
+ public String readString() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= remaining()) {
+ // TODO(nathanmittler): Is there a way to avoid this copy?
+ byte[] bytes = copyToArray(pos, pos + size);
+ String result = new String(bytes, UTF_8);
+ pos += size;
+ return result;
+ }
+
if (size == 0) {
- return Internal.EMPTY_BYTE_ARRAY;
- } else {
+ return "";
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @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?
+ byte[] bytes = copyToArray(pos, pos + 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;
+ }
+
+ if (size == 0) {
+ return "";
+ }
+ if (size <= 0) {
throw InvalidProtocolBufferException.negativeSize();
}
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public void readGroup(
+ final int fieldNumber,
+ final MessageLite.Builder builder,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
}
- // Verify that the message size so far has not exceeded sizeLimit.
- int currentMessageSize = totalBytesRetired + bufferPos + size;
- if (currentMessageSize > sizeLimit) {
- throw InvalidProtocolBufferException.sizeLimitExceeded();
+
+ @Override
+ public <T extends MessageLite> T readGroup(
+ final int fieldNumber,
+ final Parser<T> parser,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ return result;
}
- // Verify that the message size so far has not exceeded currentLimit.
- if (currentMessageSize > currentLimit) {
- // Read to the end of the stream anyway.
- skipRawBytes(currentLimit - totalBytesRetired - bufferPos);
+ @Deprecated
+ @Override
+ public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder)
+ throws IOException {
+ readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry());
+ }
+
+ @Override
+ public void readMessage(
+ final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ final int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ }
+
+
+ @Override
+ public <T extends MessageLite> T readMessage(
+ final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException {
+ int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ return result;
+ }
+
+ @Override
+ public ByteString readBytes() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= remaining()) {
+ ByteBuffer result;
+ if (immutable && enableAliasing) {
+ result = slice(pos, pos + size);
+ } else {
+ result = copy(pos, pos + size);
+ }
+ pos += size;
+ return ByteString.wrap(result);
+ }
+
+ if (size == 0) {
+ return ByteString.EMPTY;
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
throw InvalidProtocolBufferException.truncatedMessage();
}
- // We need the input stream to proceed.
- if (input == null) {
+ @Override
+ public byte[] readByteArray() throws IOException {
+ return readRawBytes(readRawVarint32());
+ }
+
+ @Override
+ public ByteBuffer readByteBuffer() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= remaining()) {
+ ByteBuffer result;
+ // "Immutable" implies that buffer is backing a ByteString.
+ // Disallow slicing in this case to prevent the caller from modifying the contents
+ // of the ByteString.
+ if (!immutable && enableAliasing) {
+ result = slice(pos, pos + size);
+ } else {
+ result = copy(pos, pos + size);
+ }
+ pos += size;
+ // TODO(nathanmittler): Investigate making the ByteBuffer be made read-only
+ return result;
+ }
+
+ if (size == 0) {
+ return EMPTY_BYTE_BUFFER;
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
throw InvalidProtocolBufferException.truncatedMessage();
}
- final int originalBufferPos = bufferPos;
- final int bufferedBytes = bufferSize - bufferPos;
+ @Override
+ public int readUInt32() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public int readEnum() throws IOException {
+ return readRawVarint32();
+ }
- // Mark the current buffer consumed.
- totalBytesRetired += bufferSize;
- bufferPos = 0;
- bufferSize = 0;
+ @Override
+ public int readSFixed32() throws IOException {
+ return readRawLittleEndian32();
+ }
- // Determine the number of bytes we need to read from the input stream.
- int sizeLeft = size - bufferedBytes;
- // TODO(nathanmittler): Consider using a value larger than BUFFER_SIZE.
- if (sizeLeft < BUFFER_SIZE || sizeLeft <= input.available()) {
- // Either the bytes we need are known to be available, or the required buffer is
- // within an allowed threshold - go ahead and allocate the buffer now.
- final byte[] bytes = new byte[size];
+ @Override
+ public long readSFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
- // Copy all of the buffered bytes to the result buffer.
- System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+ @Override
+ public int readSInt32() throws IOException {
+ return decodeZigZag32(readRawVarint32());
+ }
+
+ @Override
+ public long readSInt64() throws IOException {
+ return decodeZigZag64(readRawVarint64());
+ }
+
+ // =================================================================
- // Fill the remaining bytes from the input stream.
- int pos = bufferedBytes;
- while (pos < bytes.length) {
- int n = input.read(bytes, pos, size - pos);
- if (n == -1) {
- throw InvalidProtocolBufferException.truncatedMessage();
+ @Override
+ public int readRawVarint32() throws IOException {
+ // See implementation notes for readRawVarint64
+ fastpath:
+ {
+ long tempPos = pos;
+
+ if (limit == tempPos) {
+ break fastpath;
+ }
+
+ int x;
+ if ((x = UnsafeUtil.getByte(tempPos++)) >= 0) {
+ pos = tempPos;
+ return x;
+ } else if (limit - tempPos < 9) {
+ break fastpath;
+ } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) {
+ x ^= (~0 << 7);
+ } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) {
+ x ^= (~0 << 7) ^ (~0 << 14);
+ } else if ((x ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) {
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21);
+ } else {
+ int y = UnsafeUtil.getByte(tempPos++);
+ x ^= y << 28;
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28);
+ if (y < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0
+ && UnsafeUtil.getByte(tempPos++) < 0) {
+ break fastpath; // Will throw malformedVarint()
+ }
}
- totalBytesRetired += n;
- pos += n;
+ pos = tempPos;
+ return x;
}
+ return (int) readRawVarint64SlowPath();
+ }
- return bytes;
+ private void skipRawVarint() throws IOException {
+ if (remaining() >= MAX_VARINT_SIZE) {
+ skipRawVarintFastPath();
+ } else {
+ skipRawVarintSlowPath();
+ }
}
- // The size is very large. For security reasons, we can't allocate the
- // entire byte array yet. The size comes directly from the input, so a
- // maliciously-crafted message could provide a bogus very large size in
- // order to trick the app into allocating a lot of memory. We avoid this
- // by allocating and reading only a small chunk at a time, so that the
- // malicious message must actually *be* extremely large to cause
- // problems. Meanwhile, we limit the allowed size of a message elsewhere.
- final List<byte[]> chunks = new ArrayList<byte[]>();
-
- while (sizeLeft > 0) {
- // TODO(nathanmittler): Consider using a value larger than BUFFER_SIZE.
- final byte[] chunk = new byte[Math.min(sizeLeft, BUFFER_SIZE)];
- int pos = 0;
- while (pos < chunk.length) {
- final int n = input.read(chunk, pos, chunk.length - pos);
- if (n == -1) {
- throw InvalidProtocolBufferException.truncatedMessage();
+ private void skipRawVarintFastPath() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (UnsafeUtil.getByte(pos++) >= 0) {
+ return;
}
- totalBytesRetired += n;
- pos += n;
}
- sizeLeft -= chunk.length;
- chunks.add(chunk);
+ throw InvalidProtocolBufferException.malformedVarint();
}
- // OK, got everything. Now concatenate it all into one buffer.
- final byte[] bytes = new byte[size];
+ private void skipRawVarintSlowPath() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (readRawByte() >= 0) {
+ return;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
- // Start by copying the leftover bytes from this.buffer.
- System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+ @Override
+ public long readRawVarint64() throws IOException {
+ // Implementation notes:
+ //
+ // Optimized for one-byte values, expected to be common.
+ // The particular code below was selected from various candidates
+ // empirically, by winning VarintBenchmark.
+ //
+ // Sign extension of (signed) Java bytes is usually a nuisance, but
+ // we exploit it here to more easily obtain the sign of bytes read.
+ // Instead of cleaning up the sign extension bits by masking eagerly,
+ // we delay until we find the final (positive) byte, when we clear all
+ // accumulated bits with one xor. We depend on javac to constant fold.
+ fastpath:
+ {
+ long tempPos = pos;
+
+ if (limit == tempPos) {
+ break fastpath;
+ }
- // And now all the chunks.
- int pos = bufferedBytes;
- for (final byte[] chunk : chunks) {
- System.arraycopy(chunk, 0, bytes, pos, chunk.length);
- pos += chunk.length;
+ long x;
+ int y;
+ if ((y = UnsafeUtil.getByte(tempPos++)) >= 0) {
+ pos = tempPos;
+ return y;
+ } else if (limit - tempPos < 9) {
+ break fastpath;
+ } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 7)) < 0) {
+ x = y ^ (~0 << 7);
+ } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 14)) >= 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14));
+ } else if ((y ^= (UnsafeUtil.getByte(tempPos++) << 21)) < 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21));
+ } else if ((x = y ^ ((long) UnsafeUtil.getByte(tempPos++) << 28)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28);
+ } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 35)) < 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35);
+ } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 42)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42);
+ } else if ((x ^= ((long) UnsafeUtil.getByte(tempPos++) << 49)) < 0L) {
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49);
+ } else {
+ x ^= ((long) UnsafeUtil.getByte(tempPos++) << 56);
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49)
+ ^ (~0L << 56);
+ if (x < 0L) {
+ if (UnsafeUtil.getByte(tempPos++) < 0L) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ }
+ pos = tempPos;
+ return x;
+ }
+ return readRawVarint64SlowPath();
}
- // Done.
- return bytes;
- }
+ @Override
+ long readRawVarint64SlowPath() throws IOException {
+ long result = 0;
+ for (int shift = 0; shift < 64; shift += 7) {
+ final byte b = readRawByte();
+ result |= (long) (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ return result;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
- /**
- * Reads and discards {@code size} bytes.
- *
- * @throws InvalidProtocolBufferException The end of the stream or the current
- * limit was reached.
- */
- public void skipRawBytes(final int size) throws IOException {
- if (size <= (bufferSize - bufferPos) && size >= 0) {
- // We have all the bytes we need already.
- bufferPos += size;
- } else {
- skipRawBytesSlowPath(size);
+ @Override
+ public int readRawLittleEndian32() throws IOException {
+ long tempPos = pos;
+
+ if (limit - tempPos < FIXED_32_SIZE) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ pos = tempPos + FIXED_32_SIZE;
+ return (((UnsafeUtil.getByte(tempPos) & 0xff))
+ | ((UnsafeUtil.getByte(tempPos + 1) & 0xff) << 8)
+ | ((UnsafeUtil.getByte(tempPos + 2) & 0xff) << 16)
+ | ((UnsafeUtil.getByte(tempPos + 3) & 0xff) << 24));
+ }
+
+ @Override
+ public long readRawLittleEndian64() throws IOException {
+ long tempPos = pos;
+
+ if (limit - tempPos < FIXED_64_SIZE) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ pos = tempPos + FIXED_64_SIZE;
+ return (((UnsafeUtil.getByte(tempPos) & 0xffL))
+ | ((UnsafeUtil.getByte(tempPos + 1) & 0xffL) << 8)
+ | ((UnsafeUtil.getByte(tempPos + 2) & 0xffL) << 16)
+ | ((UnsafeUtil.getByte(tempPos + 3) & 0xffL) << 24)
+ | ((UnsafeUtil.getByte(tempPos + 4) & 0xffL) << 32)
+ | ((UnsafeUtil.getByte(tempPos + 5) & 0xffL) << 40)
+ | ((UnsafeUtil.getByte(tempPos + 6) & 0xffL) << 48)
+ | ((UnsafeUtil.getByte(tempPos + 7) & 0xffL) << 56));
+ }
+
+ @Override
+ public void enableAliasing(boolean enabled) {
+ this.enableAliasing = enabled;
+ }
+
+ @Override
+ public void resetSizeCounter() {
+ startPos = pos;
+ }
+
+ @Override
+ public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
+ if (byteLimit < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ byteLimit += getTotalBytesRead();
+ final int oldLimit = currentLimit;
+ if (byteLimit > oldLimit) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ currentLimit = byteLimit;
+
+ recomputeBufferSizeAfterLimit();
+
+ return oldLimit;
+ }
+
+ @Override
+ public void popLimit(final int oldLimit) {
+ currentLimit = oldLimit;
+ recomputeBufferSizeAfterLimit();
+ }
+
+ @Override
+ public int getBytesUntilLimit() {
+ if (currentLimit == Integer.MAX_VALUE) {
+ return -1;
+ }
+
+ return currentLimit - getTotalBytesRead();
+ }
+
+ @Override
+ public boolean isAtEnd() throws IOException {
+ return pos == limit;
+ }
+
+ @Override
+ public int getTotalBytesRead() {
+ return (int) (pos - startPos);
+ }
+
+ @Override
+ public byte readRawByte() throws IOException {
+ if (pos == limit) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ return UnsafeUtil.getByte(pos++);
+ }
+
+ @Override
+ public byte[] readRawBytes(final int length) throws IOException {
+ if (length >= 0 && length <= remaining()) {
+ byte[] bytes = new byte[length];
+ slice(pos, pos + length).get(bytes);
+ pos += length;
+ return bytes;
+ }
+
+ if (length <= 0) {
+ if (length == 0) {
+ return EMPTY_BYTE_ARRAY;
+ } else {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ }
+
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ @Override
+ public void skipRawBytes(final int length) throws IOException {
+ if (length >= 0 && length <= remaining()) {
+ // We have all the bytes we need already.
+ pos += length;
+ return;
+ }
+
+ if (length < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ private void recomputeBufferSizeAfterLimit() {
+ limit += bufferSizeAfterLimit;
+ final int bufferEnd = (int) (limit - startPos);
+ if (bufferEnd > currentLimit) {
+ // Limit is in current buffer.
+ bufferSizeAfterLimit = bufferEnd - currentLimit;
+ limit -= bufferSizeAfterLimit;
+ } else {
+ bufferSizeAfterLimit = 0;
+ }
+ }
+
+ private int remaining() {
+ return (int) (limit - pos);
+ }
+
+ private int bufferPos(long pos) {
+ return (int) (pos - address);
+ }
+
+ private ByteBuffer slice(long begin, long end) throws IOException {
+ int prevPos = buffer.position();
+ int prevLimit = buffer.limit();
+ try {
+ buffer.position(bufferPos(begin));
+ buffer.limit(bufferPos(end));
+ return buffer.slice();
+ } catch (IllegalArgumentException e) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ } finally {
+ buffer.position(prevPos);
+ buffer.limit(prevLimit);
+ }
+ }
+
+ private ByteBuffer copy(long begin, long end) throws IOException {
+ return ByteBuffer.wrap(copyToArray(begin, end));
+ }
+
+ private byte[] copyToArray(long begin, long end) throws IOException {
+ int prevPos = buffer.position();
+ int prevLimit = buffer.limit();
+ try {
+ buffer.position(bufferPos(begin));
+ buffer.limit(bufferPos(end));
+ byte[] bytes = new byte[(int) (end - begin)];
+ buffer.get(bytes);
+ return bytes;
+ } catch (IllegalArgumentException e) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ } finally {
+ buffer.position(prevPos);
+ buffer.limit(prevLimit);
+ }
}
}
/**
- * Exactly like skipRawBytes, but caller must have already checked the fast
- * path: (size <= (bufferSize - pos) && size >= 0)
+ * Implementation of {@link CodedInputStream} that uses an {@link InputStream} as the data source.
*/
- private void skipRawBytesSlowPath(final int size) throws IOException {
- if (size < 0) {
- throw InvalidProtocolBufferException.negativeSize();
+ private static final class StreamDecoder extends CodedInputStream {
+ private final InputStream input;
+ private final byte[] buffer;
+ /** bufferSize represents how many bytes are currently filled in the buffer */
+ private int bufferSize;
+
+ private int bufferSizeAfterLimit;
+ private int pos;
+ private int lastTag;
+
+ /**
+ * The total number of bytes read before the current buffer. The total bytes read up to the
+ * current position can be computed as {@code totalBytesRetired + pos}. This value may be
+ * negative if reading started in the middle of the current buffer (e.g. if the constructor that
+ * takes a byte array and an offset was used).
+ */
+ private int totalBytesRetired;
+
+ /** The absolute position of the end of the current message. */
+ private int currentLimit = Integer.MAX_VALUE;
+
+ private StreamDecoder(final InputStream input, int bufferSize) {
+ checkNotNull(input, "input");
+ this.input = input;
+ this.buffer = new byte[bufferSize];
+ this.bufferSize = 0;
+ pos = 0;
+ totalBytesRetired = 0;
}
- if (totalBytesRetired + bufferPos + size > currentLimit) {
- // Read to the end of the stream anyway.
- skipRawBytes(currentLimit - totalBytesRetired - bufferPos);
- // Then fail.
- throw InvalidProtocolBufferException.truncatedMessage();
+ @Override
+ public int readTag() throws IOException {
+ if (isAtEnd()) {
+ lastTag = 0;
+ return 0;
+ }
+
+ lastTag = readRawVarint32();
+ if (WireFormat.getTagFieldNumber(lastTag) == 0) {
+ // If we actually read zero (or any tag number corresponding to field
+ // number zero), that's not a valid tag.
+ throw InvalidProtocolBufferException.invalidTag();
+ }
+ return lastTag;
}
- // Skipping more bytes than are in the buffer. First skip what we have.
- int pos = bufferSize - bufferPos;
- bufferPos = bufferSize;
+ @Override
+ public void checkLastTagWas(final int value) throws InvalidProtocolBufferException {
+ if (lastTag != value) {
+ throw InvalidProtocolBufferException.invalidEndTag();
+ }
+ }
- // Keep refilling the buffer until we get to the point we wanted to skip to.
- // This has the side effect of ensuring the limits are updated correctly.
- refillBuffer(1);
- while (size - pos > bufferSize) {
- pos += bufferSize;
- bufferPos = bufferSize;
- refillBuffer(1);
+ @Override
+ public int getLastTag() {
+ return lastTag;
+ }
+
+ @Override
+ public boolean skipField(final int tag) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ skipRawVarint();
+ return true;
+ case WireFormat.WIRETYPE_FIXED64:
+ skipRawBytes(FIXED_64_SIZE);
+ return true;
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ skipRawBytes(readRawVarint32());
+ return true;
+ case WireFormat.WIRETYPE_START_GROUP:
+ skipMessage();
+ checkLastTagWas(
+ WireFormat.makeTag(WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP));
+ return true;
+ case WireFormat.WIRETYPE_END_GROUP:
+ return false;
+ case WireFormat.WIRETYPE_FIXED32:
+ skipRawBytes(FIXED_32_SIZE);
+ return true;
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public boolean skipField(final int tag, final CodedOutputStream output) throws IOException {
+ switch (WireFormat.getTagWireType(tag)) {
+ case WireFormat.WIRETYPE_VARINT:
+ {
+ long value = readInt64();
+ output.writeRawVarint32(tag);
+ output.writeUInt64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_FIXED64:
+ {
+ long value = readRawLittleEndian64();
+ output.writeRawVarint32(tag);
+ output.writeFixed64NoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_LENGTH_DELIMITED:
+ {
+ ByteString value = readBytes();
+ output.writeRawVarint32(tag);
+ output.writeBytesNoTag(value);
+ return true;
+ }
+ case WireFormat.WIRETYPE_START_GROUP:
+ {
+ output.writeRawVarint32(tag);
+ skipMessage(output);
+ int endtag =
+ WireFormat.makeTag(
+ WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
+ checkLastTagWas(endtag);
+ output.writeRawVarint32(endtag);
+ return true;
+ }
+ case WireFormat.WIRETYPE_END_GROUP:
+ {
+ return false;
+ }
+ case WireFormat.WIRETYPE_FIXED32:
+ {
+ int value = readRawLittleEndian32();
+ output.writeRawVarint32(tag);
+ output.writeFixed32NoTag(value);
+ return true;
+ }
+ default:
+ throw InvalidProtocolBufferException.invalidWireType();
+ }
+ }
+
+ @Override
+ public void skipMessage() throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag)) {
+ return;
+ }
+ }
+ }
+
+ @Override
+ public void skipMessage(CodedOutputStream output) throws IOException {
+ while (true) {
+ final int tag = readTag();
+ if (tag == 0 || !skipField(tag, output)) {
+ return;
+ }
+ }
+ }
+
+ /** Collects the bytes skipped and returns the data in a ByteBuffer. */
+ private class SkippedDataSink implements RefillCallback {
+ private int lastPos = pos;
+ private ByteArrayOutputStream byteArrayStream;
+
+ @Override
+ public void onRefill() {
+ if (byteArrayStream == null) {
+ byteArrayStream = new ByteArrayOutputStream();
+ }
+ byteArrayStream.write(buffer, lastPos, pos - lastPos);
+ lastPos = 0;
+ }
+
+ /** Gets skipped data in a ByteBuffer. This method should only be called once. */
+ ByteBuffer getSkippedData() {
+ if (byteArrayStream == null) {
+ return ByteBuffer.wrap(buffer, lastPos, pos - lastPos);
+ } else {
+ byteArrayStream.write(buffer, lastPos, pos);
+ return ByteBuffer.wrap(byteArrayStream.toByteArray());
+ }
+ }
+ }
+
+
+ // -----------------------------------------------------------------
+
+ @Override
+ public double readDouble() throws IOException {
+ return Double.longBitsToDouble(readRawLittleEndian64());
+ }
+
+ @Override
+ public float readFloat() throws IOException {
+ return Float.intBitsToFloat(readRawLittleEndian32());
+ }
+
+ @Override
+ public long readUInt64() throws IOException {
+ return readRawVarint64();
+ }
+
+ @Override
+ public long readInt64() throws IOException {
+ return readRawVarint64();
+ }
+
+ @Override
+ public int readInt32() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public long readFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
+
+ @Override
+ public int readFixed32() throws IOException {
+ return readRawLittleEndian32();
}
- bufferPos = size - pos;
+ @Override
+ public boolean readBool() throws IOException {
+ return readRawVarint64() != 0;
+ }
+
+ @Override
+ public String readString() throws IOException {
+ final int size = readRawVarint32();
+ if (size > 0 && size <= (bufferSize - pos)) {
+ // Fast path: We already have the bytes in a contiguous buffer, so
+ // just copy directly from it.
+ final String result = new String(buffer, pos, size, UTF_8);
+ pos += size;
+ return result;
+ }
+ if (size == 0) {
+ return "";
+ }
+ if (size <= bufferSize) {
+ refillBuffer(size);
+ String result = new String(buffer, pos, size, UTF_8);
+ pos += size;
+ return result;
+ }
+ // Slow path: Build a byte array first then copy it.
+ return new String(readRawBytesSlowPath(size), UTF_8);
+ }
+
+ @Override
+ public String readStringRequireUtf8() throws IOException {
+ final int size = readRawVarint32();
+ final byte[] bytes;
+ final int oldPos = pos;
+ final int tempPos;
+ if (size <= (bufferSize - oldPos) && size > 0) {
+ // Fast path: We already have the bytes in a contiguous buffer, so
+ // just copy directly from it.
+ bytes = buffer;
+ pos = oldPos + size;
+ tempPos = oldPos;
+ } else if (size == 0) {
+ return "";
+ } else if (size <= bufferSize) {
+ refillBuffer(size);
+ bytes = buffer;
+ tempPos = 0;
+ pos = tempPos + size;
+ } else {
+ // Slow path: Build a byte array first then copy it.
+ 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();
+ }
+ return new String(bytes, tempPos, size, UTF_8);
+ }
+
+ @Override
+ public void readGroup(
+ final int fieldNumber,
+ final MessageLite.Builder builder,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ }
+
+
+ @Override
+ public <T extends MessageLite> T readGroup(
+ final int fieldNumber,
+ final Parser<T> parser,
+ final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(WireFormat.makeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP));
+ --recursionDepth;
+ return result;
+ }
+
+ @Deprecated
+ @Override
+ public void readUnknownGroup(final int fieldNumber, final MessageLite.Builder builder)
+ throws IOException {
+ readGroup(fieldNumber, builder, ExtensionRegistryLite.getEmptyRegistry());
+ }
+
+ @Override
+ public void readMessage(
+ final MessageLite.Builder builder, final ExtensionRegistryLite extensionRegistry)
+ throws IOException {
+ final int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ builder.mergeFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ }
+
+
+ @Override
+ public <T extends MessageLite> T readMessage(
+ final Parser<T> parser, final ExtensionRegistryLite extensionRegistry) throws IOException {
+ int length = readRawVarint32();
+ if (recursionDepth >= recursionLimit) {
+ throw InvalidProtocolBufferException.recursionLimitExceeded();
+ }
+ final int oldLimit = pushLimit(length);
+ ++recursionDepth;
+ T result = parser.parsePartialFrom(this, extensionRegistry);
+ checkLastTagWas(0);
+ --recursionDepth;
+ popLimit(oldLimit);
+ return result;
+ }
+
+ @Override
+ public ByteString readBytes() throws IOException {
+ final int size = readRawVarint32();
+ if (size <= (bufferSize - pos) && size > 0) {
+ // Fast path: We already have the bytes in a contiguous buffer, so
+ // just copy directly from it.
+ final ByteString result = ByteString.copyFrom(buffer, pos, size);
+ pos += size;
+ return result;
+ }
+ if (size == 0) {
+ return ByteString.EMPTY;
+ }
+ // Slow path: Build a byte array first then copy it.
+ return ByteString.wrap(readRawBytesSlowPath(size));
+ }
+
+ @Override
+ public byte[] readByteArray() throws IOException {
+ final int size = readRawVarint32();
+ if (size <= (bufferSize - pos) && size > 0) {
+ // Fast path: We already have the bytes in a contiguous buffer, so
+ // just copy directly from it.
+ final byte[] result = Arrays.copyOfRange(buffer, pos, pos + size);
+ pos += size;
+ return result;
+ } else {
+ // Slow path: Build a byte array first then copy it.
+ return readRawBytesSlowPath(size);
+ }
+ }
+
+ @Override
+ public ByteBuffer readByteBuffer() throws IOException {
+ final int size = readRawVarint32();
+ if (size <= (bufferSize - pos) && size > 0) {
+ // Fast path: We already have the bytes in a contiguous buffer.
+ ByteBuffer result = ByteBuffer.wrap(Arrays.copyOfRange(buffer, pos, pos + size));
+ pos += size;
+ return result;
+ }
+ if (size == 0) {
+ return Internal.EMPTY_BYTE_BUFFER;
+ }
+ // Slow path: Build a byte array first then copy it.
+ return ByteBuffer.wrap(readRawBytesSlowPath(size));
+ }
+
+ @Override
+ public int readUInt32() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public int readEnum() throws IOException {
+ return readRawVarint32();
+ }
+
+ @Override
+ public int readSFixed32() throws IOException {
+ return readRawLittleEndian32();
+ }
+
+ @Override
+ public long readSFixed64() throws IOException {
+ return readRawLittleEndian64();
+ }
+
+ @Override
+ public int readSInt32() throws IOException {
+ return decodeZigZag32(readRawVarint32());
+ }
+
+ @Override
+ public long readSInt64() throws IOException {
+ return decodeZigZag64(readRawVarint64());
+ }
+
+ // =================================================================
+
+ @Override
+ public int readRawVarint32() throws IOException {
+ // See implementation notes for readRawVarint64
+ fastpath:
+ {
+ int tempPos = pos;
+
+ if (bufferSize == tempPos) {
+ break fastpath;
+ }
+
+ final byte[] buffer = this.buffer;
+ int x;
+ if ((x = buffer[tempPos++]) >= 0) {
+ pos = tempPos;
+ return x;
+ } else if (bufferSize - tempPos < 9) {
+ break fastpath;
+ } else if ((x ^= (buffer[tempPos++] << 7)) < 0) {
+ x ^= (~0 << 7);
+ } else if ((x ^= (buffer[tempPos++] << 14)) >= 0) {
+ x ^= (~0 << 7) ^ (~0 << 14);
+ } else if ((x ^= (buffer[tempPos++] << 21)) < 0) {
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21);
+ } else {
+ int y = buffer[tempPos++];
+ x ^= y << 28;
+ x ^= (~0 << 7) ^ (~0 << 14) ^ (~0 << 21) ^ (~0 << 28);
+ if (y < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0
+ && buffer[tempPos++] < 0) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ pos = tempPos;
+ return x;
+ }
+ return (int) readRawVarint64SlowPath();
+ }
+
+ private void skipRawVarint() throws IOException {
+ if (bufferSize - pos >= MAX_VARINT_SIZE) {
+ skipRawVarintFastPath();
+ } else {
+ skipRawVarintSlowPath();
+ }
+ }
+
+ private void skipRawVarintFastPath() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (buffer[pos++] >= 0) {
+ return;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ private void skipRawVarintSlowPath() throws IOException {
+ for (int i = 0; i < MAX_VARINT_SIZE; i++) {
+ if (readRawByte() >= 0) {
+ return;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ @Override
+ public long readRawVarint64() throws IOException {
+ // Implementation notes:
+ //
+ // Optimized for one-byte values, expected to be common.
+ // The particular code below was selected from various candidates
+ // empirically, by winning VarintBenchmark.
+ //
+ // Sign extension of (signed) Java bytes is usually a nuisance, but
+ // we exploit it here to more easily obtain the sign of bytes read.
+ // Instead of cleaning up the sign extension bits by masking eagerly,
+ // we delay until we find the final (positive) byte, when we clear all
+ // accumulated bits with one xor. We depend on javac to constant fold.
+ fastpath:
+ {
+ int tempPos = pos;
+
+ if (bufferSize == tempPos) {
+ break fastpath;
+ }
+
+ final byte[] buffer = this.buffer;
+ long x;
+ int y;
+ if ((y = buffer[tempPos++]) >= 0) {
+ pos = tempPos;
+ return y;
+ } else if (bufferSize - tempPos < 9) {
+ break fastpath;
+ } else if ((y ^= (buffer[tempPos++] << 7)) < 0) {
+ x = y ^ (~0 << 7);
+ } else if ((y ^= (buffer[tempPos++] << 14)) >= 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14));
+ } else if ((y ^= (buffer[tempPos++] << 21)) < 0) {
+ x = y ^ ((~0 << 7) ^ (~0 << 14) ^ (~0 << 21));
+ } else if ((x = y ^ ((long) buffer[tempPos++] << 28)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28);
+ } else if ((x ^= ((long) buffer[tempPos++] << 35)) < 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35);
+ } else if ((x ^= ((long) buffer[tempPos++] << 42)) >= 0L) {
+ x ^= (~0L << 7) ^ (~0L << 14) ^ (~0L << 21) ^ (~0L << 28) ^ (~0L << 35) ^ (~0L << 42);
+ } else if ((x ^= ((long) buffer[tempPos++] << 49)) < 0L) {
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49);
+ } else {
+ x ^= ((long) buffer[tempPos++] << 56);
+ x ^=
+ (~0L << 7)
+ ^ (~0L << 14)
+ ^ (~0L << 21)
+ ^ (~0L << 28)
+ ^ (~0L << 35)
+ ^ (~0L << 42)
+ ^ (~0L << 49)
+ ^ (~0L << 56);
+ if (x < 0L) {
+ if (buffer[tempPos++] < 0L) {
+ break fastpath; // Will throw malformedVarint()
+ }
+ }
+ }
+ pos = tempPos;
+ return x;
+ }
+ return readRawVarint64SlowPath();
+ }
+
+ @Override
+ long readRawVarint64SlowPath() throws IOException {
+ long result = 0;
+ for (int shift = 0; shift < 64; shift += 7) {
+ final byte b = readRawByte();
+ result |= (long) (b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ return result;
+ }
+ }
+ throw InvalidProtocolBufferException.malformedVarint();
+ }
+
+ @Override
+ public int readRawLittleEndian32() throws IOException {
+ int tempPos = pos;
+
+ if (bufferSize - tempPos < FIXED_32_SIZE) {
+ refillBuffer(FIXED_32_SIZE);
+ tempPos = pos;
+ }
+
+ final byte[] buffer = this.buffer;
+ pos = tempPos + FIXED_32_SIZE;
+ return (((buffer[tempPos] & 0xff))
+ | ((buffer[tempPos + 1] & 0xff) << 8)
+ | ((buffer[tempPos + 2] & 0xff) << 16)
+ | ((buffer[tempPos + 3] & 0xff) << 24));
+ }
+
+ @Override
+ public long readRawLittleEndian64() throws IOException {
+ int tempPos = pos;
+
+ if (bufferSize - tempPos < FIXED_64_SIZE) {
+ refillBuffer(FIXED_64_SIZE);
+ tempPos = pos;
+ }
+
+ final byte[] buffer = this.buffer;
+ pos = tempPos + FIXED_64_SIZE;
+ return (((buffer[tempPos] & 0xffL))
+ | ((buffer[tempPos + 1] & 0xffL) << 8)
+ | ((buffer[tempPos + 2] & 0xffL) << 16)
+ | ((buffer[tempPos + 3] & 0xffL) << 24)
+ | ((buffer[tempPos + 4] & 0xffL) << 32)
+ | ((buffer[tempPos + 5] & 0xffL) << 40)
+ | ((buffer[tempPos + 6] & 0xffL) << 48)
+ | ((buffer[tempPos + 7] & 0xffL) << 56));
+ }
+
+ // -----------------------------------------------------------------
+
+ @Override
+ public void enableAliasing(boolean enabled) {
+ // TODO(nathanmittler): Ideally we should throw here. Do nothing for backward compatibility.
+ }
+
+ @Override
+ public void resetSizeCounter() {
+ totalBytesRetired = -pos;
+ }
+
+ @Override
+ public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
+ if (byteLimit < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+ byteLimit += totalBytesRetired + pos;
+ final int oldLimit = currentLimit;
+ if (byteLimit > oldLimit) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ currentLimit = byteLimit;
+
+ recomputeBufferSizeAfterLimit();
+
+ return oldLimit;
+ }
+
+ private void recomputeBufferSizeAfterLimit() {
+ bufferSize += bufferSizeAfterLimit;
+ final int bufferEnd = totalBytesRetired + bufferSize;
+ if (bufferEnd > currentLimit) {
+ // Limit is in current buffer.
+ bufferSizeAfterLimit = bufferEnd - currentLimit;
+ bufferSize -= bufferSizeAfterLimit;
+ } else {
+ bufferSizeAfterLimit = 0;
+ }
+ }
+
+ @Override
+ public void popLimit(final int oldLimit) {
+ currentLimit = oldLimit;
+ recomputeBufferSizeAfterLimit();
+ }
+
+ @Override
+ public int getBytesUntilLimit() {
+ if (currentLimit == Integer.MAX_VALUE) {
+ return -1;
+ }
+
+ final int currentAbsolutePosition = totalBytesRetired + pos;
+ return currentLimit - currentAbsolutePosition;
+ }
+
+ @Override
+ public boolean isAtEnd() throws IOException {
+ return pos == bufferSize && !tryRefillBuffer(1);
+ }
+
+ @Override
+ public int getTotalBytesRead() {
+ return totalBytesRetired + pos;
+ }
+
+ private interface RefillCallback {
+ void onRefill();
+ }
+
+ private RefillCallback refillCallback = null;
+
+ /**
+ * Reads more bytes from the input, making at least {@code n} bytes available in the buffer.
+ * Caller must ensure that the requested space is not yet available, and that the requested
+ * space is less than BUFFER_SIZE.
+ *
+ * @throws InvalidProtocolBufferException The end of the stream or the current limit was
+ * reached.
+ */
+ private void refillBuffer(int n) throws IOException {
+ if (!tryRefillBuffer(n)) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ }
+
+ /**
+ * Tries to read more bytes from the input, making at least {@code n} bytes available in the
+ * buffer. Caller must ensure that the requested space is not yet available, and that the
+ * requested space is less than BUFFER_SIZE.
+ *
+ * @return {@code true} if the bytes could be made available; {@code false} if the end of the
+ * stream or the current limit was reached.
+ */
+ private boolean tryRefillBuffer(int n) throws IOException {
+ if (pos + n <= bufferSize) {
+ throw new IllegalStateException(
+ "refillBuffer() called when " + n + " bytes were already available in buffer");
+ }
+
+ if (totalBytesRetired + pos + n > currentLimit) {
+ // Oops, we hit a limit.
+ return false;
+ }
+
+ if (refillCallback != null) {
+ refillCallback.onRefill();
+ }
+
+ int tempPos = pos;
+ if (tempPos > 0) {
+ if (bufferSize > tempPos) {
+ System.arraycopy(buffer, tempPos, buffer, 0, bufferSize - tempPos);
+ }
+ totalBytesRetired += tempPos;
+ bufferSize -= tempPos;
+ pos = 0;
+ }
+
+ int bytesRead = input.read(buffer, bufferSize, buffer.length - bufferSize);
+ if (bytesRead == 0 || bytesRead < -1 || bytesRead > buffer.length) {
+ throw new IllegalStateException(
+ "InputStream#read(byte[]) returned invalid result: "
+ + bytesRead
+ + "\nThe InputStream implementation is buggy.");
+ }
+ if (bytesRead > 0) {
+ bufferSize += bytesRead;
+ // Integer-overflow-conscious check against sizeLimit
+ if (totalBytesRetired + n - sizeLimit > 0) {
+ throw InvalidProtocolBufferException.sizeLimitExceeded();
+ }
+ recomputeBufferSizeAfterLimit();
+ return (bufferSize >= n) ? true : tryRefillBuffer(n);
+ }
+
+ return false;
+ }
+
+ @Override
+ public byte readRawByte() throws IOException {
+ if (pos == bufferSize) {
+ refillBuffer(1);
+ }
+ return buffer[pos++];
+ }
+
+ @Override
+ public byte[] readRawBytes(final int size) throws IOException {
+ final int tempPos = pos;
+ if (size <= (bufferSize - tempPos) && size > 0) {
+ pos = tempPos + size;
+ return Arrays.copyOfRange(buffer, tempPos, tempPos + size);
+ } else {
+ return readRawBytesSlowPath(size);
+ }
+ }
+
+ /**
+ * Exactly like readRawBytes, but caller must have already checked the fast path: (size <=
+ * (bufferSize - pos) && size > 0)
+ */
+ private byte[] readRawBytesSlowPath(final int size) throws IOException {
+ if (size == 0) {
+ return Internal.EMPTY_BYTE_ARRAY;
+ }
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+
+ // Verify that the message size so far has not exceeded sizeLimit.
+ int currentMessageSize = totalBytesRetired + pos + size;
+ if (currentMessageSize > sizeLimit) {
+ throw InvalidProtocolBufferException.sizeLimitExceeded();
+ }
+
+ // Verify that the message size so far has not exceeded currentLimit.
+ if (currentMessageSize > currentLimit) {
+ // Read to the end of the stream anyway.
+ skipRawBytes(currentLimit - totalBytesRetired - pos);
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ final int originalBufferPos = pos;
+ final int bufferedBytes = bufferSize - pos;
+
+ // Mark the current buffer consumed.
+ totalBytesRetired += bufferSize;
+ pos = 0;
+ bufferSize = 0;
+
+ // Determine the number of bytes we need to read from the input stream.
+ int sizeLeft = size - bufferedBytes;
+ // TODO(nathanmittler): Consider using a value larger than DEFAULT_BUFFER_SIZE.
+ if (sizeLeft < DEFAULT_BUFFER_SIZE || sizeLeft <= input.available()) {
+ // Either the bytes we need are known to be available, or the required buffer is
+ // within an allowed threshold - go ahead and allocate the buffer now.
+ final byte[] bytes = new byte[size];
+
+ // Copy all of the buffered bytes to the result buffer.
+ System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+
+ // Fill the remaining bytes from the input stream.
+ int tempPos = bufferedBytes;
+ while (tempPos < bytes.length) {
+ int n = input.read(bytes, tempPos, size - tempPos);
+ if (n == -1) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ totalBytesRetired += n;
+ tempPos += n;
+ }
+
+ return bytes;
+ }
+
+ // The size is very large. For security reasons, we can't allocate the
+ // entire byte array yet. The size comes directly from the input, so a
+ // maliciously-crafted message could provide a bogus very large size in
+ // order to trick the app into allocating a lot of memory. We avoid this
+ // by allocating and reading only a small chunk at a time, so that the
+ // malicious message must actually *be* extremely large to cause
+ // problems. Meanwhile, we limit the allowed size of a message elsewhere.
+ final List<byte[]> chunks = new ArrayList<byte[]>();
+
+ while (sizeLeft > 0) {
+ // TODO(nathanmittler): Consider using a value larger than DEFAULT_BUFFER_SIZE.
+ final byte[] chunk = new byte[Math.min(sizeLeft, DEFAULT_BUFFER_SIZE)];
+ int tempPos = 0;
+ while (tempPos < chunk.length) {
+ final int n = input.read(chunk, tempPos, chunk.length - tempPos);
+ if (n == -1) {
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+ totalBytesRetired += n;
+ tempPos += n;
+ }
+ sizeLeft -= chunk.length;
+ chunks.add(chunk);
+ }
+
+ // OK, got everything. Now concatenate it all into one buffer.
+ final byte[] bytes = new byte[size];
+
+ // Start by copying the leftover bytes from this.buffer.
+ System.arraycopy(buffer, originalBufferPos, bytes, 0, bufferedBytes);
+
+ // And now all the chunks.
+ int tempPos = bufferedBytes;
+ for (final byte[] chunk : chunks) {
+ System.arraycopy(chunk, 0, bytes, tempPos, chunk.length);
+ tempPos += chunk.length;
+ }
+
+ // Done.
+ return bytes;
+ }
+
+ @Override
+ public void skipRawBytes(final int size) throws IOException {
+ if (size <= (bufferSize - pos) && size >= 0) {
+ // We have all the bytes we need already.
+ pos += size;
+ } else {
+ skipRawBytesSlowPath(size);
+ }
+ }
+
+ /**
+ * Exactly like skipRawBytes, but caller must have already checked the fast path: (size <=
+ * (bufferSize - pos) && size >= 0)
+ */
+ private void skipRawBytesSlowPath(final int size) throws IOException {
+ if (size < 0) {
+ throw InvalidProtocolBufferException.negativeSize();
+ }
+
+ if (totalBytesRetired + pos + size > currentLimit) {
+ // Read to the end of the stream anyway.
+ skipRawBytes(currentLimit - totalBytesRetired - pos);
+ // Then fail.
+ throw InvalidProtocolBufferException.truncatedMessage();
+ }
+
+ // Skipping more bytes than are in the buffer. First skip what we have.
+ int tempPos = bufferSize - pos;
+ pos = bufferSize;
+
+ // Keep refilling the buffer until we get to the point we wanted to skip to.
+ // This has the side effect of ensuring the limits are updated correctly.
+ refillBuffer(1);
+ while (size - tempPos > bufferSize) {
+ tempPos += bufferSize;
+ pos = bufferSize;
+ refillBuffer(1);
+ }
+
+ pos = size - tempPos;
+ }
}
}
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 e5515285..3e32c2c5 100644
--- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
+++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
@@ -30,10 +30,12 @@
package com.google.protobuf;
+import static com.google.protobuf.WireFormat.FIXED_32_SIZE;
+import static com.google.protobuf.WireFormat.FIXED_64_SIZE;
+import static com.google.protobuf.WireFormat.MAX_VARINT_SIZE;
import static java.lang.Math.max;
import com.google.protobuf.Utf8.UnpairedSurrogateException;
-
import java.io.IOException;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
@@ -59,10 +61,6 @@ public abstract class CodedOutputStream extends ByteOutput {
private static final boolean HAS_UNSAFE_ARRAY_OPERATIONS = UnsafeUtil.hasUnsafeArrayOperations();
private static final long ARRAY_BASE_OFFSET = UnsafeUtil.getArrayBaseOffset();
- private static final int FIXED_32_SIZE = 4;
- private static final int FIXED_64_SIZE = 8;
- private static final int MAX_VARINT_SIZE = 10;
-
/**
* @deprecated Use {@link #computeFixed32SizeNoTag(int)} instead.
*/
@@ -134,14 +132,27 @@ public abstract class CodedOutputStream extends ByteOutput {
return new ArrayEncoder(flatArray, offset, length);
}
- /**
- * Create a new {@code CodedOutputStream} that writes to the given {@link ByteBuffer}.
- */
- public static CodedOutputStream newInstance(ByteBuffer byteBuffer) {
- if (byteBuffer.hasArray()) {
- return new NioHeapEncoder(byteBuffer);
+ /** Create a new {@code CodedOutputStream} that writes to the given {@link ByteBuffer}. */
+ public static CodedOutputStream newInstance(ByteBuffer buffer) {
+ if (buffer.hasArray()) {
+ return new HeapNioEncoder(buffer);
}
- return new NioEncoder(byteBuffer);
+ if (buffer.isDirect() && !buffer.isReadOnly()) {
+ return UnsafeDirectNioEncoder.isSupported()
+ ? newUnsafeInstance(buffer)
+ : newSafeInstance(buffer);
+ }
+ throw new IllegalArgumentException("ByteBuffer is read-only");
+ }
+
+ /** For testing purposes only. */
+ static CodedOutputStream newUnsafeInstance(ByteBuffer buffer) {
+ return new UnsafeDirectNioEncoder(buffer);
+ }
+
+ /** For testing purposes only. */
+ static CodedOutputStream newSafeInstance(ByteBuffer buffer) {
+ return new SafeDirectNioEncoder(buffer);
}
/**
@@ -979,6 +990,10 @@ public abstract class CodedOutputStream extends ByteOutput {
super(MESSAGE);
}
+ OutOfSpaceException(String explanationMessage) {
+ super(MESSAGE + ": " + explanationMessage);
+ }
+
OutOfSpaceException(Throwable cause) {
super(MESSAGE, cause);
}
@@ -1486,11 +1501,11 @@ public abstract class CodedOutputStream extends ByteOutput {
* A {@link CodedOutputStream} that writes directly to a heap {@link ByteBuffer}. Writes are
* done directly to the underlying array. The buffer position is only updated after a flush.
*/
- private static final class NioHeapEncoder extends ArrayEncoder {
+ private static final class HeapNioEncoder extends ArrayEncoder {
private final ByteBuffer byteBuffer;
private int initialPosition;
- NioHeapEncoder(ByteBuffer byteBuffer) {
+ HeapNioEncoder(ByteBuffer byteBuffer) {
super(byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(),
byteBuffer.remaining());
this.byteBuffer = byteBuffer;
@@ -1505,14 +1520,15 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
- * A {@link CodedOutputStream} that writes directly to a {@link ByteBuffer}.
+ * A {@link CodedOutputStream} that writes directly to a direct {@link ByteBuffer}, using only
+ * safe operations..
*/
- private static final class NioEncoder extends CodedOutputStream {
+ private static final class SafeDirectNioEncoder extends CodedOutputStream {
private final ByteBuffer originalBuffer;
private final ByteBuffer buffer;
private final int initialPosition;
- NioEncoder(ByteBuffer buffer) {
+ SafeDirectNioEncoder(ByteBuffer buffer) {
this.originalBuffer = buffer;
this.buffer = buffer.duplicate().order(ByteOrder.LITTLE_ENDIAN);
initialPosition = buffer.position();
@@ -1815,6 +1831,356 @@ public abstract class CodedOutputStream extends ByteOutput {
}
/**
+ * A {@link CodedOutputStream} that writes directly to a direct {@link ByteBuffer} using {@code
+ * sun.misc.Unsafe}.
+ */
+ private static final class UnsafeDirectNioEncoder extends CodedOutputStream {
+ private final ByteBuffer originalBuffer;
+ private final ByteBuffer buffer;
+ private final long address;
+ private final long initialPosition;
+ private final long limit;
+ private final long oneVarintLimit;
+ private long position;
+
+ UnsafeDirectNioEncoder(ByteBuffer buffer) {
+ this.originalBuffer = buffer;
+ this.buffer = buffer.duplicate().order(ByteOrder.LITTLE_ENDIAN);
+ address = UnsafeUtil.addressOffset(buffer);
+ initialPosition = address + buffer.position();
+ limit = address + buffer.limit();
+ oneVarintLimit = limit - MAX_VARINT_SIZE;
+ position = initialPosition;
+ }
+
+ static boolean isSupported() {
+ return UnsafeUtil.hasUnsafeByteBufferOperations();
+ }
+
+ @Override
+ public void writeTag(int fieldNumber, int wireType) throws IOException {
+ writeUInt32NoTag(WireFormat.makeTag(fieldNumber, wireType));
+ }
+
+ @Override
+ public void writeInt32(int fieldNumber, int value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
+ writeInt32NoTag(value);
+ }
+
+ @Override
+ public void writeUInt32(int fieldNumber, int value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
+ writeUInt32NoTag(value);
+ }
+
+ @Override
+ public void writeFixed32(int fieldNumber, int value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
+ writeFixed32NoTag(value);
+ }
+
+ @Override
+ public void writeUInt64(int fieldNumber, long value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
+ writeUInt64NoTag(value);
+ }
+
+ @Override
+ public void writeFixed64(int fieldNumber, long value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
+ writeFixed64NoTag(value);
+ }
+
+ @Override
+ public void writeBool(int fieldNumber, boolean value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
+ write((byte) (value ? 1 : 0));
+ }
+
+ @Override
+ public void writeString(int fieldNumber, String value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ writeStringNoTag(value);
+ }
+
+ @Override
+ public void writeBytes(int fieldNumber, ByteString value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ writeBytesNoTag(value);
+ }
+
+ @Override
+ public void writeByteArray(int fieldNumber, byte[] value) throws IOException {
+ writeByteArray(fieldNumber, value, 0, value.length);
+ }
+
+ @Override
+ public void writeByteArray(int fieldNumber, byte[] value, int offset, int length)
+ throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ writeByteArrayNoTag(value, offset, length);
+ }
+
+ @Override
+ public void writeByteBuffer(int fieldNumber, ByteBuffer value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ writeUInt32NoTag(value.capacity());
+ writeRawBytes(value);
+ }
+
+ @Override
+ public void writeMessage(int fieldNumber, MessageLite value) throws IOException {
+ writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
+ writeMessageNoTag(value);
+ }
+
+ @Override
+ public void writeMessageSetExtension(int fieldNumber, MessageLite value) throws IOException {
+ writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
+ writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
+ writeMessage(WireFormat.MESSAGE_SET_MESSAGE, value);
+ writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
+ }
+
+ @Override
+ public void writeRawMessageSetExtension(int fieldNumber, ByteString value) throws IOException {
+ writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
+ writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
+ writeBytes(WireFormat.MESSAGE_SET_MESSAGE, value);
+ writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
+ }
+
+ @Override
+ public void writeMessageNoTag(MessageLite value) throws IOException {
+ writeUInt32NoTag(value.getSerializedSize());
+ value.writeTo(this);
+ }
+
+ @Override
+ public void write(byte value) throws IOException {
+ if (position >= limit) {
+ throw new OutOfSpaceException(
+ String.format("Pos: %d, limit: %d, len: %d", position, limit, 1));
+ }
+ UnsafeUtil.putByte(position++, value);
+ }
+
+ @Override
+ public void writeBytesNoTag(ByteString value) throws IOException {
+ writeUInt32NoTag(value.size());
+ value.writeTo(this);
+ }
+
+ @Override
+ public void writeByteArrayNoTag(byte[] value, int offset, int length) throws IOException {
+ writeUInt32NoTag(length);
+ write(value, offset, length);
+ }
+
+ @Override
+ public void writeRawBytes(ByteBuffer value) throws IOException {
+ if (value.hasArray()) {
+ write(value.array(), value.arrayOffset(), value.capacity());
+ } else {
+ ByteBuffer duplicated = value.duplicate();
+ duplicated.clear();
+ write(duplicated);
+ }
+ }
+
+ @Override
+ public void writeInt32NoTag(int value) throws IOException {
+ if (value >= 0) {
+ writeUInt32NoTag(value);
+ } else {
+ // Must sign-extend.
+ writeUInt64NoTag(value);
+ }
+ }
+
+ @Override
+ public void writeUInt32NoTag(int value) throws IOException {
+ if (position <= oneVarintLimit) {
+ // Optimization to avoid bounds checks on each iteration.
+ while (true) {
+ if ((value & ~0x7F) == 0) {
+ UnsafeUtil.putByte(position++, (byte) value);
+ return;
+ } else {
+ UnsafeUtil.putByte(position++, (byte) ((value & 0x7F) | 0x80));
+ value >>>= 7;
+ }
+ }
+ } else {
+ while (position < limit) {
+ if ((value & ~0x7F) == 0) {
+ UnsafeUtil.putByte(position++, (byte) value);
+ return;
+ } else {
+ UnsafeUtil.putByte(position++, (byte) ((value & 0x7F) | 0x80));
+ value >>>= 7;
+ }
+ }
+ throw new OutOfSpaceException(
+ String.format("Pos: %d, limit: %d, len: %d", position, limit, 1));
+ }
+ }
+
+ @Override
+ public void writeFixed32NoTag(int value) throws IOException {
+ buffer.putInt(bufferPos(position), value);
+ position += FIXED_32_SIZE;
+ }
+
+ @Override
+ public void writeUInt64NoTag(long value) throws IOException {
+ if (position <= oneVarintLimit) {
+ // Optimization to avoid bounds checks on each iteration.
+ while (true) {
+ if ((value & ~0x7FL) == 0) {
+ UnsafeUtil.putByte(position++, (byte) value);
+ return;
+ } else {
+ UnsafeUtil.putByte(position++, (byte) (((int) value & 0x7F) | 0x80));
+ value >>>= 7;
+ }
+ }
+ } else {
+ while (position < limit) {
+ if ((value & ~0x7FL) == 0) {
+ UnsafeUtil.putByte(position++, (byte) value);
+ return;
+ } else {
+ UnsafeUtil.putByte(position++, (byte) (((int) value & 0x7F) | 0x80));
+ value >>>= 7;
+ }
+ }
+ throw new OutOfSpaceException(
+ String.format("Pos: %d, limit: %d, len: %d", position, limit, 1));
+ }
+ }
+
+ @Override
+ public void writeFixed64NoTag(long value) throws IOException {
+ buffer.putLong(bufferPos(position), value);
+ position += FIXED_64_SIZE;
+ }
+
+ @Override
+ public void write(byte[] value, int offset, int length) throws IOException {
+ if (value == null
+ || offset < 0
+ || length < 0
+ || (value.length - length) < offset
+ || (limit - length) < position) {
+ if (value == null) {
+ throw new NullPointerException("value");
+ }
+ throw new OutOfSpaceException(
+ String.format("Pos: %d, limit: %d, len: %d", position, limit, length));
+ }
+
+ UnsafeUtil.copyMemory(
+ value, UnsafeUtil.getArrayBaseOffset() + offset, null, position, length);
+ position += length;
+ }
+
+ @Override
+ public void writeLazy(byte[] value, int offset, int length) throws IOException {
+ write(value, offset, length);
+ }
+
+ @Override
+ public void write(ByteBuffer value) throws IOException {
+ try {
+ int length = value.remaining();
+ repositionBuffer(position);
+ buffer.put(value);
+ position += length;
+ } catch (BufferOverflowException e) {
+ throw new OutOfSpaceException(e);
+ }
+ }
+
+ @Override
+ public void writeLazy(ByteBuffer value) throws IOException {
+ write(value);
+ }
+
+ @Override
+ public void writeStringNoTag(String value) throws IOException {
+ long prevPos = position;
+ try {
+ // 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. We take advantage of this in both branches below.
+ int maxEncodedSize = value.length() * Utf8.MAX_BYTES_PER_CHAR;
+ int maxLengthVarIntSize = computeUInt32SizeNoTag(maxEncodedSize);
+ int minLengthVarIntSize = computeUInt32SizeNoTag(value.length());
+ if (minLengthVarIntSize == maxLengthVarIntSize) {
+ // Save the current position and increment past the length field. We'll come back
+ // and write the length field after the encoding is complete.
+ int stringStart = bufferPos(position) + minLengthVarIntSize;
+ buffer.position(stringStart);
+
+ // Encode the string.
+ Utf8.encodeUtf8(value, buffer);
+
+ // Write the length and advance the position.
+ int length = buffer.position() - stringStart;
+ writeUInt32NoTag(length);
+ position += length;
+ } else {
+ // Calculate and write the encoded length.
+ int length = Utf8.encodedLength(value);
+ writeUInt32NoTag(length);
+
+ // Write the string and advance the position.
+ repositionBuffer(position);
+ Utf8.encodeUtf8(value, buffer);
+ position += length;
+ }
+ } catch (UnpairedSurrogateException e) {
+ // Roll back the change and convert to an IOException.
+ position = prevPos;
+ repositionBuffer(position);
+
+ // TODO(nathanmittler): We should throw an IOException here instead.
+ inefficientWriteStringNoTag(value, e);
+ } catch (IllegalArgumentException e) {
+ // Thrown by buffer.position() if out of range.
+ throw new OutOfSpaceException(e);
+ } catch (IndexOutOfBoundsException e) {
+ throw new OutOfSpaceException(e);
+ }
+ }
+
+ @Override
+ public void flush() {
+ // Update the position of the original buffer.
+ originalBuffer.position(bufferPos(position));
+ }
+
+ @Override
+ public int spaceLeft() {
+ return (int) (limit - position);
+ }
+
+ @Override
+ public int getTotalBytesWritten() {
+ return (int) (position - initialPosition);
+ }
+
+ private void repositionBuffer(long pos) {
+ buffer.position(bufferPos(pos));
+ }
+
+ private int bufferPos(long pos) {
+ return (int) (pos - address);
+ }
+ }
+
+ /**
* Abstract base class for buffered encoders.
*/
private abstract static class AbstractBufferedEncoder extends CodedOutputStream {
diff --git a/java/core/src/main/java/com/google/protobuf/Descriptors.java b/java/core/src/main/java/com/google/protobuf/Descriptors.java
index 1c34c24f..cab7118a 100644
--- a/java/core/src/main/java/com/google/protobuf/Descriptors.java
+++ b/java/core/src/main/java/com/google/protobuf/Descriptors.java
@@ -1212,33 +1212,20 @@ public final class Descriptors {
private final Object defaultDefault;
}
- // TODO(xiaofeng): Implement it consistently across different languages. See b/24751348.
- private static String fieldNameToLowerCamelCase(String name) {
+ // This method should match exactly with the ToJsonName() function in C++
+ // descriptor.cc.
+ private static String fieldNameToJsonName(String name) {
StringBuilder result = new StringBuilder(name.length());
boolean isNextUpperCase = false;
for (int i = 0; i < name.length(); i++) {
Character ch = name.charAt(i);
- if (Character.isLowerCase(ch)) {
- if (isNextUpperCase) {
- result.append(Character.toUpperCase(ch));
- } else {
- result.append(ch);
- }
- isNextUpperCase = false;
- } else if (Character.isUpperCase(ch)) {
- if (i == 0) {
- // Force first letter to lower-case.
- result.append(Character.toLowerCase(ch));
- } else {
- // Capital letters after the first are left as-is.
- result.append(ch);
- }
- isNextUpperCase = false;
- } else if (Character.isDigit(ch)) {
- result.append(ch);
+ if (ch == '_') {
+ isNextUpperCase = true;
+ } else if (isNextUpperCase) {
+ result.append(Character.toUpperCase(ch));
isNextUpperCase = false;
} else {
- isNextUpperCase = true;
+ result.append(ch);
}
}
return result.toString();
@@ -1257,7 +1244,7 @@ public final class Descriptors {
if (proto.hasJsonName()) {
jsonName = proto.getJsonName();
} else {
- jsonName = fieldNameToLowerCamelCase(proto.getName());
+ jsonName = fieldNameToJsonName(proto.getName());
}
if (proto.hasType()) {
diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
index 5dfe7ff7..4cbbd296 100644
--- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
+++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java
@@ -45,6 +45,7 @@ import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
@@ -1609,24 +1610,6 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
FieldDescriptor getDescriptor();
}
- private abstract static class CachedDescriptorRetriever
- implements ExtensionDescriptorRetriever {
- private volatile FieldDescriptor descriptor;
- protected abstract FieldDescriptor loadDescriptor();
-
- @Override
- public FieldDescriptor getDescriptor() {
- if (descriptor == null) {
- synchronized (this) {
- if (descriptor == null) {
- descriptor = loadDescriptor();
- }
- }
- }
- return descriptor;
- }
- }
-
// =================================================================
/** Calls Class.getMethod and throws a RuntimeException if it fails. */
@@ -2223,6 +2206,20 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
field.getNumber());
}
+ private Message coerceType(Message value) {
+ if (value == null) {
+ return null;
+ }
+ if (mapEntryMessageDefaultInstance.getClass().isInstance(value)) {
+ return value;
+ }
+ // The value is not the exact right message type. However, if it
+ // is an alternative implementation of the same type -- e.g. a
+ // DynamicMessage -- we should accept it. In this case we can make
+ // a copy of the message.
+ return mapEntryMessageDefaultInstance.toBuilder().mergeFrom(value).build();
+ }
+
@Override
public Object get(GeneratedMessageV3 message) {
List result = new ArrayList();
@@ -2278,15 +2275,15 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
public Object getRepeatedRaw(Builder builder, int index) {
return getRepeated(builder, index);
}
-
+
@Override
public void setRepeated(Builder builder, int index, Object value) {
- getMutableMapField(builder).getMutableList().set(index, (Message) value);
+ getMutableMapField(builder).getMutableList().set(index, coerceType((Message) value));
}
@Override
public void addRepeated(Builder builder, Object value) {
- getMutableMapField(builder).getMutableList().add((Message) value);
+ getMutableMapField(builder).getMutableList().add(coerceType((Message) value));
}
@Override
@@ -2713,4 +2710,131 @@ public abstract class GeneratedMessageV3 extends AbstractMessage
output.writeBytesNoTag((ByteString) value);
}
}
+
+ protected static <V> void serializeIntegerMapTo(
+ CodedOutputStream out,
+ MapField<Integer, V> field,
+ MapEntry<Integer, V> defaultEntry,
+ int fieldNumber) throws IOException {
+ Map<Integer, V> m = field.getMap();
+ if (!out.isSerializationDeterministic()) {
+ serializeMapTo(out, m, defaultEntry, fieldNumber);
+ return;
+ }
+ // Sorting the unboxed keys and then look up the values during serialziation is 2x faster
+ // than sorting map entries with a custom comparator directly.
+ int[] keys = new int[m.size()];
+ int index = 0;
+ for (int k : m.keySet()) {
+ keys[index++] = k;
+ }
+ Arrays.sort(keys);
+ for (int key : keys) {
+ out.writeMessage(fieldNumber,
+ defaultEntry.newBuilderForType()
+ .setKey(key)
+ .setValue(m.get(key))
+ .build());
+ }
+ }
+
+ protected static <V> void serializeLongMapTo(
+ CodedOutputStream out,
+ MapField<Long, V> field,
+ MapEntry<Long, V> defaultEntry,
+ int fieldNumber)
+ throws IOException {
+ Map<Long, V> m = field.getMap();
+ if (!out.isSerializationDeterministic()) {
+ serializeMapTo(out, m, defaultEntry, fieldNumber);
+ return;
+ }
+
+ long[] keys = new long[m.size()];
+ int index = 0;
+ for (long k : m.keySet()) {
+ keys[index++] = k;
+ }
+ Arrays.sort(keys);
+ for (long key : keys) {
+ out.writeMessage(fieldNumber,
+ defaultEntry.newBuilderForType()
+ .setKey(key)
+ .setValue(m.get(key))
+ .build());
+ }
+ }
+
+ protected static <V> void serializeStringMapTo(
+ CodedOutputStream out,
+ MapField<String, V> field,
+ MapEntry<String, V> defaultEntry,
+ int fieldNumber)
+ throws IOException {
+ Map<String, V> m = field.getMap();
+ if (!out.isSerializationDeterministic()) {
+ serializeMapTo(out, m, defaultEntry, fieldNumber);
+ return;
+ }
+
+ // Sorting the String keys and then look up the values during serialziation is 25% faster than
+ // sorting map entries with a custom comparator directly.
+ String[] keys = new String[m.size()];
+ keys = m.keySet().toArray(keys);
+ Arrays.sort(keys);
+ for (String key : keys) {
+ out.writeMessage(fieldNumber,
+ defaultEntry.newBuilderForType()
+ .setKey(key)
+ .setValue(m.get(key))
+ .build());
+ }
+ }
+
+ protected static <V> void serializeBooleanMapTo(
+ CodedOutputStream out,
+ MapField<Boolean, V> field,
+ MapEntry<Boolean, V> defaultEntry,
+ int fieldNumber)
+ throws IOException {
+ Map<Boolean, V> m = field.getMap();
+ if (!out.isSerializationDeterministic()) {
+ serializeMapTo(out, m, defaultEntry, fieldNumber);
+ return;
+ }
+ maybeSerializeBooleanEntryTo(out, m, defaultEntry, fieldNumber, false);
+ maybeSerializeBooleanEntryTo(out, m, defaultEntry, fieldNumber, true);
+ }
+
+ private static <V> void maybeSerializeBooleanEntryTo(
+ CodedOutputStream out,
+ Map<Boolean, V> m,
+ MapEntry<Boolean, V> defaultEntry,
+ int fieldNumber,
+ boolean key)
+ throws IOException {
+ if (m.containsKey(key)) {
+ out.writeMessage(fieldNumber,
+ defaultEntry.newBuilderForType()
+ .setKey(key)
+ .setValue(m.get(key))
+ .build());
+ }
+ }
+
+ /** Serialize the map using the iteration order. */
+ private static <K, V> void serializeMapTo(
+ CodedOutputStream out,
+ Map<K, V> m,
+ MapEntry<K, V> defaultEntry,
+ int fieldNumber)
+ throws IOException {
+ for (Map.Entry<K, V> entry : m.entrySet()) {
+ out.writeMessage(fieldNumber,
+ defaultEntry.newBuilderForType()
+ .setKey(entry.getKey())
+ .setValue(entry.getValue())
+ .build());
+ }
+ }
}
diff --git a/java/core/src/main/java/com/google/protobuf/Internal.java b/java/core/src/main/java/com/google/protobuf/Internal.java
index 3b4a0412..c234559c 100644
--- a/java/core/src/main/java/com/google/protobuf/Internal.java
+++ b/java/core/src/main/java/com/google/protobuf/Internal.java
@@ -60,6 +60,16 @@ public final class Internal {
static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
/**
+ * Throws an appropriate {@link NullPointerException} if the given objects is {@code null}.
+ */
+ static <T> T checkNotNull(T obj, String message) {
+ if (obj == null) {
+ throw new NullPointerException(message);
+ }
+ return obj;
+ }
+
+ /**
* Helper called by generated code to construct default values for string
* fields.
* <p>
diff --git a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
index 85ce7b24..55e33d21 100644
--- a/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
+++ b/java/core/src/main/java/com/google/protobuf/InvalidProtocolBufferException.java
@@ -107,11 +107,23 @@ public class InvalidProtocolBufferException extends IOException {
"Protocol message end-group tag did not match expected tag.");
}
- static InvalidProtocolBufferException invalidWireType() {
- return new InvalidProtocolBufferException(
+ static InvalidWireTypeException invalidWireType() {
+ return new InvalidWireTypeException(
"Protocol message tag had invalid wire type.");
}
+ /**
+ * Exception indicating that and unexpected wire type was encountered for a field.
+ */
+ @ExperimentalApi
+ public static class InvalidWireTypeException extends InvalidProtocolBufferException {
+ private static final long serialVersionUID = 3283890091615336259L;
+
+ public InvalidWireTypeException(String description) {
+ super(description);
+ }
+ }
+
static InvalidProtocolBufferException recursionLimitExceeded() {
return new InvalidProtocolBufferException(
"Protocol message had too many levels of nesting. May be malicious. " +
diff --git a/java/core/src/main/java/com/google/protobuf/MapEntry.java b/java/core/src/main/java/com/google/protobuf/MapEntry.java
index 117cd911..4f0351f4 100644
--- a/java/core/src/main/java/com/google/protobuf/MapEntry.java
+++ b/java/core/src/main/java/com/google/protobuf/MapEntry.java
@@ -334,6 +334,15 @@ public final class MapEntry<K, V> extends AbstractMessage {
} else {
if (field.getType() == FieldDescriptor.Type.ENUM) {
value = ((EnumValueDescriptor) value).getNumber();
+ } else if (field.getType() == FieldDescriptor.Type.MESSAGE) {
+ if (value != null && !metadata.defaultValue.getClass().isInstance(value)) {
+ // The value is not the exact right message type. However, if it
+ // is an alternative implementation of the same type -- e.g. a
+ // DynamicMessage -- we should accept it. In this case we can make
+ // a copy of the message.
+ value =
+ ((Message) metadata.defaultValue).toBuilder().mergeFrom((Message) value).build();
+ }
}
setValue((V) value);
}
diff --git a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
index 3c0ad89a..16b3fefe 100644
--- a/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
+++ b/java/core/src/main/java/com/google/protobuf/MapFieldLite.java
@@ -58,7 +58,7 @@ public final class MapFieldLite<K, V> extends LinkedHashMap<K, V> {
}
@SuppressWarnings({"rawtypes", "unchecked"})
- private static final MapFieldLite EMPTY_MAP_FIELD = new MapFieldLite(Collections.emptyMap());
+ private static final MapFieldLite EMPTY_MAP_FIELD = new MapFieldLite();
static {
EMPTY_MAP_FIELD.makeImmutable();
}
diff --git a/java/core/src/main/java/com/google/protobuf/NioByteString.java b/java/core/src/main/java/com/google/protobuf/NioByteString.java
index 6163c7b1..76594809 100644
--- a/java/core/src/main/java/com/google/protobuf/NioByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/NioByteString.java
@@ -30,6 +30,8 @@
package com.google.protobuf;
+import static com.google.protobuf.Internal.checkNotNull;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
@@ -49,10 +51,9 @@ final class NioByteString extends ByteString.LeafByteString {
private final ByteBuffer buffer;
NioByteString(ByteBuffer buffer) {
- if (buffer == null) {
- throw new NullPointerException("buffer");
- }
+ checkNotNull(buffer, "buffer");
+ // Use native byte order for fast fixed32/64 operations.
this.buffer = buffer.slice().order(ByteOrder.nativeOrder());
}
@@ -266,7 +267,7 @@ final class NioByteString extends ByteString.LeafByteString {
@Override
public CodedInputStream newCodedInput() {
- return CodedInputStream.newInstance(buffer);
+ return CodedInputStream.newInstance(buffer, true);
}
/**
diff --git a/java/core/src/main/java/com/google/protobuf/RopeByteString.java b/java/core/src/main/java/com/google/protobuf/RopeByteString.java
index 3f3e9bd1..6fa555df 100644
--- a/java/core/src/main/java/com/google/protobuf/RopeByteString.java
+++ b/java/core/src/main/java/com/google/protobuf/RopeByteString.java
@@ -406,6 +406,7 @@ final class RopeByteString extends ByteString {
right.writeTo(output);
}
+
@Override
protected String toStringInternal(Charset charset) {
return new String(toByteArray(), charset);
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 ff13675d..49708242 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java
@@ -1576,14 +1576,22 @@ public final class TextFormat {
// Support specifying repeated field values as a comma-separated list.
// Ex."foo: [1, 2, 3]"
if (field.isRepeated() && tokenizer.tryConsume("[")) {
- while (true) {
- consumeFieldValue(tokenizer, extensionRegistry, target, field, extension,
- parseTreeBuilder, unknownFields);
- if (tokenizer.tryConsume("]")) {
- // End of list.
- break;
+ if (!tokenizer.tryConsume("]")) { // Allow "foo: []" to be treated as empty.
+ while (true) {
+ consumeFieldValue(
+ tokenizer,
+ extensionRegistry,
+ target,
+ field,
+ extension,
+ parseTreeBuilder,
+ unknownFields);
+ if (tokenizer.tryConsume("]")) {
+ // End of list.
+ break;
+ }
+ tokenizer.consume(",");
}
- tokenizer.consume(",");
}
} else {
consumeFieldValue(tokenizer, extensionRegistry, target, field,
diff --git a/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java b/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java
index 5c43b2c3..0127ce92 100644
--- a/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java
+++ b/java/core/src/main/java/com/google/protobuf/TextFormatParseInfoTree.java
@@ -45,7 +45,8 @@ import java.util.Map.Entry;
*
* <p>The locations of primary fields values are retrieved by {@code getLocation} or
* {@code getLocations}. The locations of sub message values are within nested
- * {@code TextFormatParseInfoTree}s and are retrieve by {@code getNestedTree} or {@code getNestedTrees}.
+ * {@code TextFormatParseInfoTree}s and are retrieve by {@code getNestedTree} or
+ * {@code getNestedTrees}.
*
* <p>The {@code TextFormatParseInfoTree} is created by a Builder.
*/
diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java
index e72a6b4d..878c7758 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeByteOperations.java
@@ -67,16 +67,34 @@ public final class UnsafeByteOperations {
/**
* An unsafe operation that returns a {@link ByteString} that is backed by the provided buffer.
*
+ * @param buffer the buffer to be wrapped
+ * @return a {@link ByteString} backed by the provided buffer
+ */
+ public static ByteString unsafeWrap(byte[] buffer) {
+ return ByteString.wrap(buffer);
+ }
+
+ /**
+ * An unsafe operation that returns a {@link ByteString} that is backed by a subregion of the
+ * provided buffer.
+ *
+ * @param buffer the buffer to be wrapped
+ * @param offset the offset of the wrapped region
+ * @param length the number of bytes of the wrapped region
+ * @return a {@link ByteString} backed by the provided buffer
+ */
+ public static ByteString unsafeWrap(byte[] buffer, int offset, int length) {
+ return ByteString.wrap(buffer, offset, length);
+ }
+
+ /**
+ * An unsafe operation that returns a {@link ByteString} that is backed by the provided buffer.
+ *
* @param buffer the Java NIO buffer to be wrapped
* @return a {@link ByteString} backed by the provided buffer
*/
public static ByteString unsafeWrap(ByteBuffer buffer) {
- if (buffer.hasArray()) {
- final int offset = buffer.arrayOffset();
- return ByteString.wrap(buffer.array(), offset + buffer.position(), buffer.remaining());
- } else {
- return new NioByteString(buffer);
- }
+ return ByteString.wrap(buffer);
}
/**
@@ -98,4 +116,5 @@ public final class UnsafeByteOperations {
public static void unsafeWriteTo(ByteString bytes, ByteOutput output) throws IOException {
bytes.writeTo(output);
}
+
}
diff --git a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
index 6a4787d1..5f7bafd6 100644
--- a/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
+++ b/java/core/src/main/java/com/google/protobuf/UnsafeUtil.java
@@ -30,17 +30,14 @@
package com.google.protobuf;
-import sun.misc.Unsafe;
-
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
+import sun.misc.Unsafe;
-/**
- * Utility class for working with unsafe operations.
- */
+/** Utility class for working with unsafe operations. */
// TODO(nathanmittler): Add support for Android Memory/MemoryBlock
final class UnsafeUtil {
private static final sun.misc.Unsafe UNSAFE = getUnsafe();
@@ -50,8 +47,7 @@ final class UnsafeUtil {
private static final long ARRAY_BASE_OFFSET = byteArrayBaseOffset();
private static final long BUFFER_ADDRESS_OFFSET = fieldOffset(field(Buffer.class, "address"));
- private UnsafeUtil() {
- }
+ private UnsafeUtil() {}
static boolean hasUnsafeArrayOperations() {
return HAS_UNSAFE_ARRAY_OPERATIONS;
@@ -61,27 +57,83 @@ final class UnsafeUtil {
return HAS_UNSAFE_BYTEBUFFER_OPERATIONS;
}
+ static Object allocateInstance(Class<?> clazz) {
+ try {
+ return UNSAFE.allocateInstance(clazz);
+ } catch (InstantiationException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ static long objectFieldOffset(Field field) {
+ return UNSAFE.objectFieldOffset(field);
+ }
+
static long getArrayBaseOffset() {
return ARRAY_BASE_OFFSET;
}
- static byte getByte(byte[] target, long offset) {
+ static byte getByte(Object target, long offset) {
return UNSAFE.getByte(target, offset);
}
- static void putByte(byte[] target, long offset, byte value) {
+ static void putByte(Object target, long offset, byte value) {
UNSAFE.putByte(target, offset, value);
}
- static void copyMemory(
- byte[] src, long srcOffset, byte[] target, long targetOffset, long length) {
- UNSAFE.copyMemory(src, srcOffset, target, targetOffset, length);
+ static int getInt(Object target, long offset) {
+ return UNSAFE.getInt(target, offset);
}
- static long getLong(byte[] target, long offset) {
+ static void putInt(Object target, long offset, int value) {
+ UNSAFE.putInt(target, offset, value);
+ }
+
+ static long getLong(Object target, long offset) {
return UNSAFE.getLong(target, offset);
}
+ static void putLong(Object target, long offset, long value) {
+ UNSAFE.putLong(target, offset, value);
+ }
+
+ static boolean getBoolean(Object target, long offset) {
+ return UNSAFE.getBoolean(target, offset);
+ }
+
+ static void putBoolean(Object target, long offset, boolean value) {
+ UNSAFE.putBoolean(target, offset, value);
+ }
+
+ static float getFloat(Object target, long offset) {
+ return UNSAFE.getFloat(target, offset);
+ }
+
+ static void putFloat(Object target, long offset, float value) {
+ UNSAFE.putFloat(target, offset, value);
+ }
+
+ static double getDouble(Object target, long offset) {
+ return UNSAFE.getDouble(target, offset);
+ }
+
+ static void putDouble(Object target, long offset, double value) {
+ UNSAFE.putDouble(target, offset, value);
+ }
+
+ static Object getObject(Object target, long offset) {
+ return UNSAFE.getObject(target, offset);
+ }
+
+ static void putObject(Object target, long offset, Object value) {
+ UNSAFE.putObject(target, offset, value);
+ }
+
+ static void copyMemory(
+ Object src, long srcOffset, Object target, long targetOffset, long length) {
+ UNSAFE.copyMemory(src, srcOffset, target, targetOffset, length);
+ }
+
static byte getByte(long address) {
return UNSAFE.getByte(address);
}
@@ -90,14 +142,30 @@ final class UnsafeUtil {
UNSAFE.putByte(address, value);
}
+ static int getInt(long address) {
+ return UNSAFE.getInt(address);
+ }
+
+ static void putInt(long address, int value) {
+ UNSAFE.putInt(address, value);
+ }
+
static long getLong(long address) {
return UNSAFE.getLong(address);
}
+ static void putLong(long address, long value) {
+ UNSAFE.putLong(address, value);
+ }
+
static void copyMemory(long srcAddress, long targetAddress, long length) {
UNSAFE.copyMemory(srcAddress, targetAddress, length);
}
+ static void setMemory(long address, long numBytes, byte value) {
+ UNSAFE.setMemory(address, numBytes, value);
+ }
+
/**
* Gets the offset of the {@code address} field of the given direct {@link ByteBuffer}.
*/
@@ -136,18 +204,29 @@ final class UnsafeUtil {
return unsafe;
}
- /**
- * Indicates whether or not unsafe array operations are supported on this platform.
- */
+ /** Indicates whether or not unsafe array operations are supported on this platform. */
private static boolean supportsUnsafeArrayOperations() {
boolean supported = false;
if (UNSAFE != null) {
try {
Class<?> clazz = UNSAFE.getClass();
+ clazz.getMethod("objectFieldOffset", Field.class);
+ clazz.getMethod("allocateInstance", Class.class);
clazz.getMethod("arrayBaseOffset", Class.class);
clazz.getMethod("getByte", Object.class, long.class);
clazz.getMethod("putByte", Object.class, long.class, byte.class);
+ clazz.getMethod("getBoolean", Object.class, long.class);
+ clazz.getMethod("putBoolean", Object.class, long.class, boolean.class);
+ clazz.getMethod("getInt", Object.class, long.class);
+ clazz.getMethod("putInt", Object.class, long.class, int.class);
clazz.getMethod("getLong", Object.class, long.class);
+ clazz.getMethod("putLong", Object.class, long.class, long.class);
+ clazz.getMethod("getFloat", Object.class, long.class);
+ clazz.getMethod("putFloat", Object.class, long.class, float.class);
+ clazz.getMethod("getDouble", Object.class, long.class);
+ clazz.getMethod("putDouble", Object.class, long.class, double.class);
+ clazz.getMethod("getObject", Object.class, long.class);
+ clazz.getMethod("putObject", Object.class, long.class, Object.class);
clazz.getMethod(
"copyMemory", Object.class, long.class, Object.class, long.class, long.class);
supported = true;
@@ -163,11 +242,17 @@ final class UnsafeUtil {
if (UNSAFE != null) {
try {
Class<?> clazz = UNSAFE.getClass();
+ // Methods for getting direct buffer address.
clazz.getMethod("objectFieldOffset", Field.class);
- clazz.getMethod("getByte", long.class);
clazz.getMethod("getLong", Object.class, long.class);
+
+ clazz.getMethod("getByte", long.class);
clazz.getMethod("putByte", long.class, byte.class);
+ clazz.getMethod("getInt", long.class);
+ clazz.getMethod("putInt", long.class, int.class);
clazz.getMethod("getLong", long.class);
+ clazz.getMethod("putLong", long.class, long.class);
+ clazz.getMethod("setMemory", long.class, long.class, byte.class);
clazz.getMethod("copyMemory", long.class, long.class, long.class);
supported = true;
} catch (Throwable e) {
diff --git a/java/core/src/main/java/com/google/protobuf/WireFormat.java b/java/core/src/main/java/com/google/protobuf/WireFormat.java
index 6a58b081..0b0cdb7d 100644
--- a/java/core/src/main/java/com/google/protobuf/WireFormat.java
+++ b/java/core/src/main/java/com/google/protobuf/WireFormat.java
@@ -47,6 +47,10 @@ public final class WireFormat {
// Do not allow instantiation.
private WireFormat() {}
+ static final int FIXED_32_SIZE = 4;
+ static final int FIXED_64_SIZE = 8;
+ static final int MAX_VARINT_SIZE = 10;
+
public static final int WIRETYPE_VARINT = 0;
public static final int WIRETYPE_FIXED64 = 1;
public static final int WIRETYPE_LENGTH_DELIMITED = 2;
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 7dc9fc15..622e36a4 100644
--- a/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
@@ -40,9 +40,8 @@ import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestRequiredForeign;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;
-import junit.framework.TestCase;
-
import java.util.Map;
+import junit.framework.TestCase;
/**
* Unit test for {@link AbstractMessage}.
@@ -492,7 +491,6 @@ public class AbstractMessageTest extends TestCase {
checkEqualsIsConsistent(eUnknownFields, eUnknownFields2);
}
-
/**
* Asserts that the given proto has symmetric equals and hashCode methods.
*/
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 ec139225..18132e9e 100644
--- a/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/BooleanArrayListTest.java
@@ -32,11 +32,10 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
+import junit.framework.TestCase;
/**
* Tests for {@link BooleanArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
index cbe742e5..6b1cfe78 100644
--- a/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ByteBufferWriterTest.java
@@ -30,13 +30,12 @@
package com.google.protobuf;
-import junit.framework.TestCase;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;
+import junit.framework.TestCase;
/**
* Tests for {@link ByteBufferWriter}.
diff --git a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
index ad9f266e..be71f1f5 100644
--- a/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ByteStringTest.java
@@ -31,9 +31,6 @@
package com.google.protobuf;
import com.google.protobuf.ByteString.Output;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -48,6 +45,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
+import junit.framework.TestCase;
/**
* Test methods with implementations in {@link ByteString}, plus do some top-level "integration"
diff --git a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
index ca940ced..e2ab0df9 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedInputStreamTest.java
@@ -30,20 +30,20 @@
package com.google.protobuf;
+import static org.junit.Assert.assertArrayEquals;
+
import protobuf_unittest.UnittestProto.BoolMessage;
import protobuf_unittest.UnittestProto.Int32Message;
import protobuf_unittest.UnittestProto.Int64Message;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestRecursiveMessage;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
+import junit.framework.TestCase;
/**
* Unit test for {@link CodedInputStream}.
@@ -51,10 +51,45 @@ import java.nio.ByteBuffer;
* @author kenton@google.com Kenton Varda
*/
public class CodedInputStreamTest extends TestCase {
+ private enum InputType {
+ ARRAY {
+ @Override
+ CodedInputStream newDecoder(byte[] data, int blockSize) {
+ return CodedInputStream.newInstance(data);
+ }
+ },
+ NIO_HEAP {
+ @Override
+ CodedInputStream newDecoder(byte[] data, int blockSize) {
+ return CodedInputStream.newInstance(ByteBuffer.wrap(data));
+ }
+ },
+ NIO_DIRECT {
+ @Override
+ CodedInputStream newDecoder(byte[] data, int blockSize) {
+ ByteBuffer buffer = ByteBuffer.allocateDirect(data.length);
+ buffer.put(data);
+ buffer.flip();
+ return CodedInputStream.newInstance(buffer);
+ }
+ },
+ STREAM {
+ @Override
+ CodedInputStream newDecoder(byte[] data, int blockSize) {
+ return CodedInputStream.newInstance(new SmallBlockInputStream(data, blockSize));
+ }
+ };
+
+ CodedInputStream newDecoder(byte[] data) {
+ return newDecoder(data, data.length);
+ }
+
+ abstract CodedInputStream newDecoder(byte[] data, int blockSize);
+ }
+
/**
- * Helper to construct a byte array from a bunch of bytes. The inputs are
- * actually ints so that I can use hex notation and not get stupid errors
- * about precision.
+ * Helper to construct a byte array from a bunch of bytes. The inputs are actually ints so that I
+ * can use hex notation and not get stupid errors about precision.
*/
private byte[] bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
@@ -65,19 +100,14 @@ public class CodedInputStreamTest extends TestCase {
}
/**
- * An InputStream which limits the number of bytes it reads at a time.
- * We use this to make sure that CodedInputStream doesn't screw up when
- * reading in small blocks.
+ * An InputStream which limits the number of bytes it reads at a time. We use this to make sure
+ * that CodedInputStream doesn't screw up when reading in small blocks.
*/
private static final class SmallBlockInputStream extends FilterInputStream {
private final int blockSize;
public SmallBlockInputStream(byte[] data, int blockSize) {
- this(new ByteArrayInputStream(data), blockSize);
- }
-
- public SmallBlockInputStream(InputStream in, int blockSize) {
- super(in);
+ super(new ByteArrayInputStream(data));
this.blockSize = blockSize;
}
@@ -92,54 +122,36 @@ public class CodedInputStreamTest extends TestCase {
}
}
- private void assertDataConsumed(byte[] data, CodedInputStream input)
+ private void assertDataConsumed(String msg, byte[] data, CodedInputStream input)
throws IOException {
- assertEquals(data.length, input.getTotalBytesRead());
- assertTrue(input.isAtEnd());
+ assertEquals(msg, data.length, input.getTotalBytesRead());
+ assertTrue(msg, input.isAtEnd());
}
/**
- * Parses the given bytes using readRawVarint32() and readRawVarint64() and
- * checks that the result matches the given value.
+ * Parses the given bytes using readRawVarint32() and readRawVarint64() and checks that the result
+ * matches the given value.
*/
private void assertReadVarint(byte[] data, long value) throws Exception {
- CodedInputStream input = CodedInputStream.newInstance(data);
- assertEquals((int) value, input.readRawVarint32());
- assertDataConsumed(data, input);
-
- input = CodedInputStream.newInstance(data);
- assertEquals(value, input.readRawVarint64());
- assertDataConsumed(data, input);
-
- input = CodedInputStream.newInstance(data);
- assertEquals(value, input.readRawVarint64SlowPath());
- assertDataConsumed(data, input);
-
- input = CodedInputStream.newInstance(data);
- assertTrue(input.skipField(WireFormat.WIRETYPE_VARINT));
- assertDataConsumed(data, input);
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
- input = CodedInputStream.newInstance(
- new SmallBlockInputStream(data, blockSize));
- assertEquals((int) value, input.readRawVarint32());
- assertDataConsumed(data, input);
-
- input = CodedInputStream.newInstance(
- new SmallBlockInputStream(data, blockSize));
- assertEquals(value, input.readRawVarint64());
- assertDataConsumed(data, input);
-
- input = CodedInputStream.newInstance(
- new SmallBlockInputStream(data, blockSize));
- assertEquals(value, input.readRawVarint64SlowPath());
- assertDataConsumed(data, input);
-
- input = CodedInputStream.newInstance(
- new SmallBlockInputStream(data, blockSize));
- assertTrue(input.skipField(WireFormat.WIRETYPE_VARINT));
- assertDataConsumed(data, input);
+ for (InputType inputType : InputType.values()) {
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
+ CodedInputStream input = inputType.newDecoder(data, blockSize);
+ assertEquals(inputType.name(), (int) value, input.readRawVarint32());
+ assertDataConsumed(inputType.name(), data, input);
+
+ input = inputType.newDecoder(data, blockSize);
+ assertEquals(inputType.name(), value, input.readRawVarint64());
+ assertDataConsumed(inputType.name(), data, input);
+
+ input = inputType.newDecoder(data, blockSize);
+ assertEquals(inputType.name(), value, input.readRawVarint64SlowPath());
+ assertDataConsumed(inputType.name(), data, input);
+
+ input = inputType.newDecoder(data, blockSize);
+ assertTrue(inputType.name(), input.skipField(WireFormat.WIRETYPE_VARINT));
+ assertDataConsumed(inputType.name(), data, input);
+ }
}
// Try reading direct from an InputStream. We want to verify that it
@@ -153,35 +165,26 @@ public class CodedInputStreamTest extends TestCase {
}
/**
- * Parses the given bytes using readRawVarint32() and readRawVarint64() and
- * expects them to fail with an InvalidProtocolBufferException whose
- * description matches the given one.
+ * Parses the given bytes using readRawVarint32() and readRawVarint64() and expects them to fail
+ * with an InvalidProtocolBufferException whose description matches the given one.
*/
- private void assertReadVarintFailure(
- InvalidProtocolBufferException expected, byte[] data)
+ private void assertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data)
throws Exception {
- CodedInputStream input = CodedInputStream.newInstance(data);
- try {
- input.readRawVarint32();
- fail("Should have thrown an exception.");
- } catch (InvalidProtocolBufferException e) {
- assertEquals(expected.getMessage(), e.getMessage());
- }
-
- input = CodedInputStream.newInstance(data);
- try {
- input.readRawVarint64();
- fail("Should have thrown an exception.");
- } catch (InvalidProtocolBufferException e) {
- assertEquals(expected.getMessage(), e.getMessage());
- }
-
- input = CodedInputStream.newInstance(data);
- try {
- input.readRawVarint64SlowPath();
- fail("Should have thrown an exception.");
- } catch (InvalidProtocolBufferException e) {
- assertEquals(expected.getMessage(), e.getMessage());
+ for (InputType inputType : InputType.values()) {
+ try {
+ CodedInputStream input = inputType.newDecoder(data);
+ input.readRawVarint32();
+ fail(inputType.name() + ": Should have thrown an exception.");
+ } catch (InvalidProtocolBufferException e) {
+ assertEquals(inputType.name(), expected.getMessage(), e.getMessage());
+ }
+ try {
+ CodedInputStream input = inputType.newDecoder(data);
+ input.readRawVarint64();
+ fail(inputType.name() + ": Should have thrown an exception.");
+ } catch (InvalidProtocolBufferException e) {
+ assertEquals(inputType.name(), expected.getMessage(), e.getMessage());
+ }
}
// Make sure we get the same error when reading direct from an InputStream.
@@ -201,72 +204,74 @@ public class CodedInputStreamTest extends TestCase {
// 14882
assertReadVarint(bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
// 2961488830
- assertReadVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
- (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
- (0x0bL << 28));
+ assertReadVarint(
+ bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bL << 28));
// 64-bit
// 7256456126
- assertReadVarint(bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
- (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
- (0x1bL << 28));
+ assertReadVarint(
+ bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
+ (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bL << 28));
// 41256202580718336
assertReadVarint(
- bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
- (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
- (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49));
+ bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
+ (0x00 << 0)
+ | (0x66 << 7)
+ | (0x6b << 14)
+ | (0x1c << 21)
+ | (0x43L << 28)
+ | (0x49L << 35)
+ | (0x24L << 42)
+ | (0x49L << 49));
// 11964378330978735131
assertReadVarint(
- bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
- (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
- (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
- (0x05L << 49) | (0x26L << 56) | (0x01L << 63));
+ bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
+ (0x1b << 0)
+ | (0x28 << 7)
+ | (0x79 << 14)
+ | (0x42 << 21)
+ | (0x3bL << 28)
+ | (0x56L << 35)
+ | (0x00L << 42)
+ | (0x05L << 49)
+ | (0x26L << 56)
+ | (0x01L << 63));
// Failures
assertReadVarintFailure(
- InvalidProtocolBufferException.malformedVarint(),
- bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
- 0x00));
- assertReadVarintFailure(
- InvalidProtocolBufferException.truncatedMessage(),
- bytes(0x80));
+ InvalidProtocolBufferException.malformedVarint(),
+ bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00));
+ assertReadVarintFailure(InvalidProtocolBufferException.truncatedMessage(), bytes(0x80));
}
/**
- * Parses the given bytes using readRawLittleEndian32() and checks
- * that the result matches the given value.
+ * Parses the given bytes using readRawLittleEndian32() and checks that the result matches the
+ * given value.
*/
- private void assertReadLittleEndian32(byte[] data, int value)
- throws Exception {
- CodedInputStream input = CodedInputStream.newInstance(data);
- assertEquals(value, input.readRawLittleEndian32());
- assertTrue(input.isAtEnd());
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
- input = CodedInputStream.newInstance(
- new SmallBlockInputStream(data, blockSize));
- assertEquals(value, input.readRawLittleEndian32());
- assertTrue(input.isAtEnd());
+ private void assertReadLittleEndian32(byte[] data, int value) throws Exception {
+ for (InputType inputType : InputType.values()) {
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
+ CodedInputStream input = inputType.newDecoder(data, blockSize);
+ assertEquals(inputType.name(), value, input.readRawLittleEndian32());
+ assertTrue(inputType.name(), input.isAtEnd());
+ }
}
}
/**
- * Parses the given bytes using readRawLittleEndian64() and checks
- * that the result matches the given value.
+ * Parses the given bytes using readRawLittleEndian64() and checks that the result matches the
+ * given value.
*/
- private void assertReadLittleEndian64(byte[] data, long value)
- throws Exception {
- CodedInputStream input = CodedInputStream.newInstance(data);
- assertEquals(value, input.readRawLittleEndian64());
- assertTrue(input.isAtEnd());
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
- input = CodedInputStream.newInstance(
- new SmallBlockInputStream(data, blockSize));
- assertEquals(value, input.readRawLittleEndian64());
- assertTrue(input.isAtEnd());
+ private void assertReadLittleEndian64(byte[] data, long value) throws Exception {
+ for (InputType inputType : InputType.values()) {
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
+ CodedInputStream input = inputType.newDecoder(data, blockSize);
+ assertEquals(inputType.name(), value, input.readRawLittleEndian64());
+ assertTrue(inputType.name(), input.isAtEnd());
+ }
}
}
@@ -276,40 +281,32 @@ public class CodedInputStreamTest extends TestCase {
assertReadLittleEndian32(bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
assertReadLittleEndian64(
- bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12),
- 0x123456789abcdef0L);
+ bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), 0x123456789abcdef0L);
assertReadLittleEndian64(
- bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a),
- 0x9abcdef012345678L);
+ bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678L);
}
/** Test decodeZigZag32() and decodeZigZag64(). */
public void testDecodeZigZag() throws Exception {
- assertEquals( 0, CodedInputStream.decodeZigZag32(0));
+ assertEquals(0, CodedInputStream.decodeZigZag32(0));
assertEquals(-1, CodedInputStream.decodeZigZag32(1));
- assertEquals( 1, CodedInputStream.decodeZigZag32(2));
+ assertEquals(1, CodedInputStream.decodeZigZag32(2));
assertEquals(-2, CodedInputStream.decodeZigZag32(3));
assertEquals(0x3FFFFFFF, CodedInputStream.decodeZigZag32(0x7FFFFFFE));
assertEquals(0xC0000000, CodedInputStream.decodeZigZag32(0x7FFFFFFF));
assertEquals(0x7FFFFFFF, CodedInputStream.decodeZigZag32(0xFFFFFFFE));
assertEquals(0x80000000, CodedInputStream.decodeZigZag32(0xFFFFFFFF));
- assertEquals( 0, CodedInputStream.decodeZigZag64(0));
+ assertEquals(0, CodedInputStream.decodeZigZag64(0));
assertEquals(-1, CodedInputStream.decodeZigZag64(1));
- assertEquals( 1, CodedInputStream.decodeZigZag64(2));
+ assertEquals(1, CodedInputStream.decodeZigZag64(2));
assertEquals(-2, CodedInputStream.decodeZigZag64(3));
- assertEquals(0x000000003FFFFFFFL,
- CodedInputStream.decodeZigZag64(0x000000007FFFFFFEL));
- assertEquals(0xFFFFFFFFC0000000L,
- CodedInputStream.decodeZigZag64(0x000000007FFFFFFFL));
- assertEquals(0x000000007FFFFFFFL,
- CodedInputStream.decodeZigZag64(0x00000000FFFFFFFEL));
- assertEquals(0xFFFFFFFF80000000L,
- CodedInputStream.decodeZigZag64(0x00000000FFFFFFFFL));
- assertEquals(0x7FFFFFFFFFFFFFFFL,
- CodedInputStream.decodeZigZag64(0xFFFFFFFFFFFFFFFEL));
- assertEquals(0x8000000000000000L,
- CodedInputStream.decodeZigZag64(0xFFFFFFFFFFFFFFFFL));
+ assertEquals(0x000000003FFFFFFFL, CodedInputStream.decodeZigZag64(0x000000007FFFFFFEL));
+ assertEquals(0xFFFFFFFFC0000000L, CodedInputStream.decodeZigZag64(0x000000007FFFFFFFL));
+ assertEquals(0x000000007FFFFFFFL, CodedInputStream.decodeZigZag64(0x00000000FFFFFFFEL));
+ assertEquals(0xFFFFFFFF80000000L, CodedInputStream.decodeZigZag64(0x00000000FFFFFFFFL));
+ assertEquals(0x7FFFFFFFFFFFFFFFL, CodedInputStream.decodeZigZag64(0xFFFFFFFFFFFFFFFEL));
+ assertEquals(0x8000000000000000L, CodedInputStream.decodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
/** Tests reading and parsing a whole message with every field type. */
@@ -319,14 +316,12 @@ public class CodedInputStreamTest extends TestCase {
byte[] rawBytes = message.toByteArray();
assertEquals(rawBytes.length, message.getSerializedSize());
- TestAllTypes message2 = TestAllTypes.parseFrom(rawBytes);
- TestUtil.assertAllFieldsSet(message2);
-
- // Try different block sizes.
- for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
- message2 = TestAllTypes.parseFrom(
- new SmallBlockInputStream(rawBytes, blockSize));
- TestUtil.assertAllFieldsSet(message2);
+ for (InputType inputType : InputType.values()) {
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize < 256; blockSize *= 2) {
+ TestAllTypes message2 = TestAllTypes.parseFrom(inputType.newDecoder(rawBytes, blockSize));
+ TestUtil.assertAllFieldsSet(message2);
+ }
}
}
@@ -335,57 +330,65 @@ public class CodedInputStreamTest extends TestCase {
TestAllTypes message = TestUtil.getAllSet();
byte[] rawBytes = message.toByteArray();
- // Create two parallel inputs. Parse one as unknown fields while using
- // skipField() to skip each field on the other. Expect the same tags.
- CodedInputStream input1 = CodedInputStream.newInstance(rawBytes);
- CodedInputStream input2 = CodedInputStream.newInstance(rawBytes);
+ InputType[] inputTypes = InputType.values();
+ CodedInputStream[] inputs = new CodedInputStream[inputTypes.length];
+ for (int i = 0; i < inputs.length; ++i) {
+ inputs[i] = inputTypes[i].newDecoder(rawBytes);
+ }
UnknownFieldSet.Builder unknownFields = UnknownFieldSet.newBuilder();
while (true) {
+ CodedInputStream input1 = inputs[0];
int tag = input1.readTag();
- assertEquals(tag, input2.readTag());
+ // Ensure that the rest match.
+ for (int i = 1; i < inputs.length; ++i) {
+ assertEquals(inputTypes[i].name(), tag, inputs[i].readTag());
+ }
if (tag == 0) {
break;
}
unknownFields.mergeFieldFrom(tag, input1);
- input2.skipField(tag);
+ // Skip the field for the rest of the inputs.
+ for (int i = 1; i < inputs.length; ++i) {
+ inputs[i].skipField(tag);
+ }
}
}
/**
- * Test that a bug in skipRawBytes() has been fixed: if the skip skips
- * exactly up to a limit, this should not break things.
+ * 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 };
- CodedInputStream input = CodedInputStream.newInstance(rawBytes);
-
- int limit = input.pushLimit(1);
- input.skipRawBytes(1);
- input.popLimit(limit);
- assertEquals(2, input.readRawByte());
+ byte[] rawBytes = new byte[] {1, 2};
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(rawBytes);
+ int limit = input.pushLimit(1);
+ input.skipRawBytes(1);
+ input.popLimit(limit);
+ assertEquals(inputType.name(), 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.
+ * 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 };
- CodedInputStream input = CodedInputStream.newInstance(
- new SmallBlockInputStream(rawBytes, 3));
-
- 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());
+ byte[] rawBytes = new byte[] {1, 2, 3, 4, 5};
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(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(inputType.name(), 1, input.readRawByte());
+ // Skip to the end of the limit.
+ input.skipRawBytes(3);
+ assertTrue(inputType.name(), input.isAtEnd());
+ input.popLimit(limit);
+ assertEquals(inputType.name(), 5, input.readRawByte());
+ }
}
public void testReadHugeBlob() throws Exception {
@@ -401,19 +404,22 @@ public class CodedInputStreamTest extends TestCase {
builder.setOptionalBytes(ByteString.copyFrom(blob));
TestAllTypes message = builder.build();
- // Serialize and parse it. Make sure to parse from an InputStream, not
- // directly from a ByteString, so that CodedInputStream uses buffered
- // reading.
- TestAllTypes message2 =
- TestAllTypes.parseFrom(message.toByteString().newInput());
-
- assertEquals(message.getOptionalBytes(), message2.getOptionalBytes());
-
- // Make sure all the other fields were parsed correctly.
- TestAllTypes message3 = TestAllTypes.newBuilder(message2)
- .setOptionalBytes(TestUtil.getAllSet().getOptionalBytes())
- .build();
- TestUtil.assertAllFieldsSet(message3);
+ byte[] data = message.toByteArray();
+ for (InputType inputType : InputType.values()) {
+ // Serialize and parse it. Make sure to parse from an InputStream, not
+ // directly from a ByteString, so that CodedInputStream uses buffered
+ // reading.
+ TestAllTypes message2 = TestAllTypes.parseFrom(inputType.newDecoder(data));
+
+ assertEquals(inputType.name(), message.getOptionalBytes(), message2.getOptionalBytes());
+
+ // Make sure all the other fields were parsed correctly.
+ TestAllTypes message3 =
+ TestAllTypes.newBuilder(message2)
+ .setOptionalBytes(TestUtil.getAllSet().getOptionalBytes())
+ .build();
+ TestUtil.assertAllFieldsSet(message3);
+ }
}
public void testReadMaliciouslyLargeBlob() throws Exception {
@@ -423,17 +429,19 @@ public class CodedInputStreamTest extends TestCase {
int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
output.writeRawVarint32(tag);
output.writeRawVarint32(0x7FFFFFFF);
- output.writeRawBytes(new byte[32]); // Pad with a few random bytes.
+ output.writeRawBytes(new byte[32]); // Pad with a few random bytes.
output.flush();
- CodedInputStream input = rawOutput.toByteString().newCodedInput();
- assertEquals(tag, input.readTag());
-
- try {
- input.readBytes();
- fail("Should have thrown an exception!");
- } catch (InvalidProtocolBufferException e) {
- // success.
+ byte[] data = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(data);
+ assertEquals(tag, input.readTag());
+ try {
+ input.readBytes();
+ fail(inputType.name() + ": Should have thrown an exception!");
+ } catch (InvalidProtocolBufferException e) {
+ // success.
+ }
}
}
@@ -441,54 +449,55 @@ public class CodedInputStreamTest extends TestCase {
if (depth == 0) {
return TestRecursiveMessage.newBuilder().setI(5).build();
} else {
- return TestRecursiveMessage.newBuilder()
- .setA(makeRecursiveMessage(depth - 1)).build();
+ return TestRecursiveMessage.newBuilder().setA(makeRecursiveMessage(depth - 1)).build();
}
}
- private void assertMessageDepth(TestRecursiveMessage message, int depth) {
+ private void assertMessageDepth(String msg, TestRecursiveMessage message, int depth) {
if (depth == 0) {
- assertFalse(message.hasA());
- assertEquals(5, message.getI());
+ assertFalse(msg, message.hasA());
+ assertEquals(msg, 5, message.getI());
} else {
- assertTrue(message.hasA());
- assertMessageDepth(message.getA(), depth - 1);
+ assertTrue(msg, message.hasA());
+ assertMessageDepth(msg, message.getA(), depth - 1);
}
}
public void testMaliciousRecursion() throws Exception {
- ByteString data100 = makeRecursiveMessage(100).toByteString();
- ByteString data101 = makeRecursiveMessage(101).toByteString();
+ byte[] data100 = makeRecursiveMessage(100).toByteArray();
+ byte[] data101 = makeRecursiveMessage(101).toByteArray();
- assertMessageDepth(TestRecursiveMessage.parseFrom(data100), 100);
+ for (InputType inputType : InputType.values()) {
+ assertMessageDepth(
+ inputType.name(), TestRecursiveMessage.parseFrom(inputType.newDecoder(data100)), 100);
- try {
- TestRecursiveMessage.parseFrom(data101);
- fail("Should have thrown an exception!");
- } catch (InvalidProtocolBufferException e) {
- // success.
- }
+ try {
+ TestRecursiveMessage.parseFrom(inputType.newDecoder(data101));
+ fail("Should have thrown an exception!");
+ } catch (InvalidProtocolBufferException e) {
+ // success.
+ }
- CodedInputStream input = data100.newCodedInput();
- input.setRecursionLimit(8);
- try {
- TestRecursiveMessage.parseFrom(input);
- fail("Should have thrown an exception!");
- } catch (InvalidProtocolBufferException e) {
- // success.
+ CodedInputStream input = inputType.newDecoder(data100);
+ input.setRecursionLimit(8);
+ try {
+ TestRecursiveMessage.parseFrom(input);
+ fail(inputType.name() + ": Should have thrown an exception!");
+ } catch (InvalidProtocolBufferException e) {
+ // success.
+ }
}
}
private void checkSizeLimitExceeded(InvalidProtocolBufferException e) {
- assertEquals(
- InvalidProtocolBufferException.sizeLimitExceeded().getMessage(),
- e.getMessage());
+ assertEquals(InvalidProtocolBufferException.sizeLimitExceeded().getMessage(), e.getMessage());
}
public void testSizeLimit() throws Exception {
- CodedInputStream input = CodedInputStream.newInstance(
- new SmallBlockInputStream(
- TestUtil.getAllSet().toByteString().newInput(), 16));
+ // NOTE: Size limit only applies to the stream-backed CIS.
+ CodedInputStream input =
+ CodedInputStream.newInstance(
+ new SmallBlockInputStream(TestUtil.getAllSet().toByteArray(), 16));
input.setSizeLimit(16);
try {
@@ -500,8 +509,9 @@ public class CodedInputStreamTest extends TestCase {
}
public void testResetSizeCounter() throws Exception {
- CodedInputStream input = CodedInputStream.newInstance(
- new SmallBlockInputStream(new byte[256], 8));
+ // NOTE: Size limit only applies to the stream-backed CIS.
+ CodedInputStream input =
+ CodedInputStream.newInstance(new SmallBlockInputStream(new byte[256], 8));
input.setSizeLimit(16);
input.readRawBytes(16);
assertEquals(16, input.getTotalBytesRead());
@@ -515,7 +525,7 @@ public class CodedInputStreamTest extends TestCase {
input.resetSizeCounter();
assertEquals(0, input.getTotalBytesRead());
- input.readRawByte(); // No exception thrown.
+ input.readRawByte(); // No exception thrown.
input.resetSizeCounter();
assertEquals(0, input.getTotalBytesRead());
input.readRawBytes(16);
@@ -523,7 +533,7 @@ public class CodedInputStreamTest extends TestCase {
input.resetSizeCounter();
try {
- input.readRawBytes(17); // Hits limit again.
+ input.readRawBytes(17); // Hits limit again.
fail("Should have thrown an exception!");
} catch (InvalidProtocolBufferException expected) {
checkSizeLimitExceeded(expected);
@@ -531,12 +541,12 @@ public class CodedInputStreamTest extends TestCase {
}
public void testSizeLimitMultipleMessages() throws Exception {
+ // NOTE: Size limit only applies to the stream-backed CIS.
byte[] bytes = new byte[256];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) i;
}
- CodedInputStream input = CodedInputStream.newInstance(
- new SmallBlockInputStream(bytes, 7));
+ CodedInputStream input = CodedInputStream.newInstance(new SmallBlockInputStream(bytes, 7));
input.setSizeLimit(16);
for (int i = 0; i < 256 / 16; i++) {
byte[] message = input.readRawBytes(16);
@@ -566,12 +576,13 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawBytes(bytes);
output.flush();
- CodedInputStream input =
- CodedInputStream.newInstance(
- new ByteArrayInputStream(rawOutput.toByteString().toByteArray()));
- assertEquals(tag, input.readTag());
- String text = input.readString();
- assertEquals(lorem, text);
+ byte[] rawInput = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(rawInput);
+ assertEquals(inputType.name(), tag, input.readTag());
+ String text = input.readString();
+ assertEquals(inputType.name(), lorem, text);
+ }
}
public void testReadStringRequireUtf8() throws Exception {
@@ -591,18 +602,18 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawBytes(bytes);
output.flush();
- CodedInputStream input =
- CodedInputStream.newInstance(
- new ByteArrayInputStream(rawOutput.toByteString().toByteArray()));
- assertEquals(tag, input.readTag());
- String text = input.readStringRequireUtf8();
- assertEquals(lorem, text);
+ byte[] rawInput = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(rawInput);
+ assertEquals(inputType.name(), tag, input.readTag());
+ String text = input.readStringRequireUtf8();
+ assertEquals(inputType.name(), lorem, text);
+ }
}
/**
- * Tests that if we readString invalid UTF-8 bytes, no exception
- * is thrown. Instead, the invalid bytes are replaced with the Unicode
- * "replacement character" U+FFFD.
+ * Tests that if we readString invalid UTF-8 bytes, no exception is thrown. Instead, the invalid
+ * bytes are replaced with the Unicode "replacement character" U+FFFD.
*/
public void testReadStringInvalidUtf8() throws Exception {
ByteString.Output rawOutput = ByteString.newOutput();
@@ -611,18 +622,21 @@ public class CodedInputStreamTest extends TestCase {
int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
output.writeRawVarint32(tag);
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[] { (byte) 0x80 });
+ output.writeRawBytes(new byte[] {(byte) 0x80});
output.flush();
- CodedInputStream input = rawOutput.toByteString().newCodedInput();
- assertEquals(tag, input.readTag());
- String text = input.readString();
- assertEquals(0xfffd, text.charAt(0));
+ byte[] rawInput = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(rawInput);
+ assertEquals(inputType.name(), tag, input.readTag());
+ String text = input.readString();
+ assertEquals(inputType.name(), 0xfffd, text.charAt(0));
+ }
}
/**
- * Tests that if we readStringRequireUtf8 invalid UTF-8 bytes, an
- * InvalidProtocolBufferException is thrown.
+ * Tests that if we readStringRequireUtf8 invalid UTF-8 bytes, an InvalidProtocolBufferException
+ * is thrown.
*/
public void testReadStringRequireUtf8InvalidUtf8() throws Exception {
ByteString.Output rawOutput = ByteString.newOutput();
@@ -631,16 +645,20 @@ public class CodedInputStreamTest extends TestCase {
int tag = WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED);
output.writeRawVarint32(tag);
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[] { (byte) 0x80 });
+ output.writeRawBytes(new byte[] {(byte) 0x80});
output.flush();
- CodedInputStream input = rawOutput.toByteString().newCodedInput();
- assertEquals(tag, input.readTag());
- try {
- input.readStringRequireUtf8();
- fail("Expected invalid UTF-8 exception.");
- } catch (InvalidProtocolBufferException exception) {
- assertEquals("Protocol message had invalid UTF-8.", exception.getMessage());
+ byte[] rawInput = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream input = inputType.newDecoder(rawInput);
+ assertEquals(tag, input.readTag());
+ try {
+ input.readStringRequireUtf8();
+ fail(inputType.name() + ": Expected invalid UTF-8 exception.");
+ } catch (InvalidProtocolBufferException exception) {
+ assertEquals(
+ inputType.name(), "Protocol message had invalid UTF-8.", exception.getMessage());
+ }
}
}
@@ -660,13 +678,17 @@ public class CodedInputStreamTest extends TestCase {
public void testInvalidTag() throws Exception {
// Any tag number which corresponds to field number zero is invalid and
// should throw InvalidProtocolBufferException.
- for (int i = 0; i < 8; i++) {
- try {
- CodedInputStream.newInstance(bytes(i)).readTag();
- fail("Should have thrown an exception.");
- } catch (InvalidProtocolBufferException e) {
- assertEquals(InvalidProtocolBufferException.invalidTag().getMessage(),
- e.getMessage());
+ for (InputType inputType : InputType.values()) {
+ for (int i = 0; i < 8; i++) {
+ try {
+ inputType.newDecoder(bytes(i)).readTag();
+ fail(inputType.name() + ": Should have thrown an exception.");
+ } catch (InvalidProtocolBufferException e) {
+ assertEquals(
+ inputType.name(),
+ InvalidProtocolBufferException.invalidTag().getMessage(),
+ e.getMessage());
+ }
}
}
}
@@ -678,10 +700,10 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawVarint32(0);
// One one-byte bytes field
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[] { (byte) 23 });
+ output.writeRawBytes(new byte[] {(byte) 23});
// Another one-byte bytes field
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[] { (byte) 45 });
+ output.writeRawBytes(new byte[] {(byte) 45});
// A bytes field large enough that won't fit into the 4K buffer.
final int bytesLength = 16 * 1024;
byte[] bytes = new byte[bytesLength];
@@ -691,20 +713,24 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawBytes(bytes);
output.flush();
- CodedInputStream inputStream = rawOutput.toByteString().newCodedInput();
-
- byte[] result = inputStream.readByteArray();
- assertEquals(0, result.length);
- result = inputStream.readByteArray();
- assertEquals(1, result.length);
- assertEquals((byte) 23, result[0]);
- result = inputStream.readByteArray();
- assertEquals(1, result.length);
- assertEquals((byte) 45, result[0]);
- result = inputStream.readByteArray();
- assertEquals(bytesLength, result.length);
- assertEquals((byte) 67, result[0]);
- assertEquals((byte) 89, result[bytesLength - 1]);
+
+ byte[] rawInput = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream inputStream = inputType.newDecoder(rawInput);
+
+ byte[] result = inputStream.readByteArray();
+ assertEquals(inputType.name(), 0, result.length);
+ result = inputStream.readByteArray();
+ assertEquals(inputType.name(), 1, result.length);
+ assertEquals(inputType.name(), (byte) 23, result[0]);
+ result = inputStream.readByteArray();
+ assertEquals(inputType.name(), 1, result.length);
+ assertEquals(inputType.name(), (byte) 45, result[0]);
+ result = inputStream.readByteArray();
+ assertEquals(inputType.name(), bytesLength, result.length);
+ assertEquals(inputType.name(), (byte) 67, result[0]);
+ assertEquals(inputType.name(), (byte) 89, result[bytesLength - 1]);
+ }
}
public void testReadByteBuffer() throws Exception {
@@ -714,10 +740,10 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawVarint32(0);
// One one-byte bytes field
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[]{(byte) 23});
+ output.writeRawBytes(new byte[] {(byte) 23});
// Another one-byte bytes field
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[]{(byte) 45});
+ output.writeRawBytes(new byte[] {(byte) 45});
// A bytes field large enough that won't fit into the 4K buffer.
final int bytesLength = 16 * 1024;
byte[] bytes = new byte[bytesLength];
@@ -727,21 +753,25 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawBytes(bytes);
output.flush();
- CodedInputStream inputStream = rawOutput.toByteString().newCodedInput();
-
- ByteBuffer result = inputStream.readByteBuffer();
- assertEquals(0, result.capacity());
- result = inputStream.readByteBuffer();
- assertEquals(1, result.capacity());
- assertEquals((byte) 23, result.get());
- result = inputStream.readByteBuffer();
- assertEquals(1, result.capacity());
- assertEquals((byte) 45, result.get());
- result = inputStream.readByteBuffer();
- assertEquals(bytesLength, result.capacity());
- assertEquals((byte) 67, result.get());
- result.position(bytesLength - 1);
- assertEquals((byte) 89, result.get());
+
+ byte[] rawInput = rawOutput.toByteString().toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream inputStream = inputType.newDecoder(rawInput);
+
+ ByteBuffer result = inputStream.readByteBuffer();
+ assertEquals(inputType.name(), 0, result.capacity());
+ result = inputStream.readByteBuffer();
+ assertEquals(inputType.name(), 1, result.capacity());
+ assertEquals(inputType.name(), (byte) 23, result.get());
+ result = inputStream.readByteBuffer();
+ assertEquals(inputType.name(), 1, result.capacity());
+ assertEquals(inputType.name(), (byte) 45, result.get());
+ result = inputStream.readByteBuffer();
+ assertEquals(inputType.name(), bytesLength, result.capacity());
+ assertEquals(inputType.name(), (byte) 67, result.get());
+ result.position(bytesLength - 1);
+ assertEquals(inputType.name(), (byte) 89, result.get());
+ }
}
public void testReadByteBufferAliasing() throws Exception {
@@ -751,10 +781,10 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawVarint32(0);
// One one-byte bytes field
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[]{(byte) 23});
+ output.writeRawBytes(new byte[] {(byte) 23});
// Another one-byte bytes field
output.writeRawVarint32(1);
- output.writeRawBytes(new byte[]{(byte) 45});
+ output.writeRawBytes(new byte[] {(byte) 45});
// A bytes field large enough that won't fit into the 4K buffer.
final int bytesLength = 16 * 1024;
byte[] bytes = new byte[bytesLength];
@@ -763,59 +793,105 @@ public class CodedInputStreamTest extends TestCase {
output.writeRawVarint32(bytesLength);
output.writeRawBytes(bytes);
output.flush();
+
byte[] data = byteArrayStream.toByteArray();
- // Without aliasing
- CodedInputStream inputStream = CodedInputStream.newInstance(data);
- ByteBuffer result = inputStream.readByteBuffer();
- assertEquals(0, result.capacity());
- result = inputStream.readByteBuffer();
- assertTrue(result.array() != data);
- assertEquals(1, result.capacity());
- assertEquals((byte) 23, result.get());
- result = inputStream.readByteBuffer();
- assertTrue(result.array() != data);
- assertEquals(1, result.capacity());
- assertEquals((byte) 45, result.get());
- result = inputStream.readByteBuffer();
- assertTrue(result.array() != data);
- assertEquals(bytesLength, result.capacity());
- assertEquals((byte) 67, result.get());
- result.position(bytesLength - 1);
- assertEquals((byte) 89, result.get());
-
- // Enable aliasing
- inputStream = CodedInputStream.newInstance(data);
- inputStream.enableAliasing(true);
- result = inputStream.readByteBuffer();
- assertEquals(0, result.capacity());
- result = inputStream.readByteBuffer();
- assertTrue(result.array() == data);
- assertEquals(1, result.capacity());
- assertEquals((byte) 23, result.get());
- result = inputStream.readByteBuffer();
- assertTrue(result.array() == data);
- assertEquals(1, result.capacity());
- assertEquals((byte) 45, result.get());
- result = inputStream.readByteBuffer();
- assertTrue(result.array() == data);
- assertEquals(bytesLength, result.capacity());
- assertEquals((byte) 67, result.get());
- result.position(bytesLength - 1);
- assertEquals((byte) 89, result.get());
+ for (InputType inputType : InputType.values()) {
+ if (inputType == InputType.STREAM) {
+ // Aliasing doesn't apply to stream-backed CIS.
+ continue;
+ }
+
+ // Without aliasing
+ CodedInputStream inputStream = inputType.newDecoder(data);
+ ByteBuffer result = inputStream.readByteBuffer();
+ assertEquals(inputType.name(), 0, result.capacity());
+ result = inputStream.readByteBuffer();
+ assertTrue(inputType.name(), result.array() != data);
+ assertEquals(inputType.name(), 1, result.capacity());
+ assertEquals(inputType.name(), (byte) 23, result.get());
+ result = inputStream.readByteBuffer();
+ assertTrue(inputType.name(), result.array() != data);
+ assertEquals(inputType.name(), 1, result.capacity());
+ assertEquals(inputType.name(), (byte) 45, result.get());
+ result = inputStream.readByteBuffer();
+ assertTrue(inputType.name(), result.array() != data);
+ assertEquals(inputType.name(), bytesLength, result.capacity());
+ assertEquals(inputType.name(), (byte) 67, result.get());
+ result.position(bytesLength - 1);
+ assertEquals(inputType.name(), (byte) 89, result.get());
+
+ // Enable aliasing
+ inputStream = inputType.newDecoder(data);
+ inputStream.enableAliasing(true);
+ result = inputStream.readByteBuffer();
+ assertEquals(inputType.name(), 0, result.capacity());
+ result = inputStream.readByteBuffer();
+ if (result.hasArray()) {
+ assertTrue(inputType.name(), result.array() == data);
+ }
+ assertEquals(inputType.name(), 1, result.capacity());
+ assertEquals(inputType.name(), (byte) 23, result.get());
+ result = inputStream.readByteBuffer();
+ if (result.hasArray()) {
+ assertTrue(inputType.name(), result.array() == data);
+ }
+ assertEquals(inputType.name(), 1, result.capacity());
+ assertEquals(inputType.name(), (byte) 45, result.get());
+ result = inputStream.readByteBuffer();
+ if (result.hasArray()) {
+ assertTrue(inputType.name(), result.array() == data);
+ }
+ assertEquals(inputType.name(), bytesLength, result.capacity());
+ assertEquals(inputType.name(), (byte) 67, result.get());
+ result.position(bytesLength - 1);
+ assertEquals(inputType.name(), (byte) 89, result.get());
+ }
}
public void testCompatibleTypes() throws Exception {
long data = 0x100000000L;
Int64Message message = Int64Message.newBuilder().setData(data).build();
- ByteString serialized = message.toByteString();
+ byte[] serialized = message.toByteArray();
+ for (InputType inputType : InputType.values()) {
+ CodedInputStream inputStream = inputType.newDecoder(serialized);
+
+ // Test int64(long) is compatible with bool(boolean)
+ BoolMessage msg2 = BoolMessage.parseFrom(inputStream);
+ assertTrue(msg2.getData());
+
+ // Test int64(long) is compatible with int32(int)
+ inputStream = inputType.newDecoder(serialized);
+ Int32Message msg3 = Int32Message.parseFrom(inputStream);
+ assertEquals((int) data, msg3.getData());
+ }
+ }
- // Test int64(long) is compatible with bool(boolean)
- BoolMessage msg2 = BoolMessage.parseFrom(serialized);
- assertTrue(msg2.getData());
+ public void testSkipInvalidVarint_FastPath() throws Exception {
+ // Fast path: We have >= 10 bytes available. Ensure we properly recognize a non-ending varint.
+ byte[] data = new byte[] {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0};
+ for (InputType inputType : InputType.values()) {
+ try {
+ CodedInputStream input = inputType.newDecoder(data);
+ input.skipField(WireFormat.makeTag(1, WireFormat.WIRETYPE_VARINT));
+ fail(inputType.name() + ": Should have thrown an exception.");
+ } catch (InvalidProtocolBufferException e) {
+ // Expected
+ }
+ }
+ }
- // Test int64(long) is compatible with int32(int)
- Int32Message msg3 = Int32Message.parseFrom(serialized);
- assertEquals((int) data, msg3.getData());
+ public void testSkipInvalidVarint_SlowPath() throws Exception {
+ // Slow path: < 10 bytes available. Ensure we properly recognize a non-ending varint.
+ byte[] data = new byte[] {-1, -1, -1, -1, -1, -1, -1, -1, -1};
+ for (InputType inputType : InputType.values()) {
+ try {
+ CodedInputStream input = inputType.newDecoder(data);
+ input.skipField(WireFormat.makeTag(1, WireFormat.WIRETYPE_VARINT));
+ fail(inputType.name() + ": Should have thrown an exception.");
+ } catch (InvalidProtocolBufferException e) {
+ // Expected
+ }
+ }
}
}
diff --git a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
index 33aa4357..78f415c2 100644
--- a/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
+++ b/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
@@ -35,15 +35,13 @@ import protobuf_unittest.UnittestProto.SparseEnumMessage;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestSparseEnum;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import junit.framework.TestCase;
/**
* Unit test for {@link CodedOutputStream}.
@@ -151,16 +149,21 @@ public class CodedOutputStreamTest extends TestCase {
private final int initialPosition;
private final CodedOutputStream stream;
private final ByteBuffer buffer;
+ private final boolean unsafe;
- NioDirectCoder(int size) {
- this(size, 0);
+ NioDirectCoder(int size, boolean unsafe) {
+ this(size, 0, unsafe);
}
- NioDirectCoder(int size, int initialPosition) {
+ NioDirectCoder(int size, int initialPosition, boolean unsafe) {
+ this.unsafe = unsafe;
this.initialPosition = initialPosition;
buffer = ByteBuffer.allocateDirect(size);
buffer.position(initialPosition);
- stream = CodedOutputStream.newInstance(buffer);
+ stream =
+ unsafe
+ ? CodedOutputStream.newUnsafeInstance(buffer)
+ : CodedOutputStream.newSafeInstance(buffer);
}
@Override
@@ -181,7 +184,7 @@ public class CodedOutputStreamTest extends TestCase {
@Override
public OutputType getOutputType() {
- return OutputType.NIO_DIRECT;
+ return unsafe ? OutputType.NIO_DIRECT_SAFE : OutputType.NIO_DIRECT_UNSAFE;
}
}
@@ -198,10 +201,16 @@ public class CodedOutputStreamTest extends TestCase {
return new NioHeapCoder(size);
}
},
- NIO_DIRECT() {
+ NIO_DIRECT_SAFE() {
@Override
Coder newCoder(int size) {
- return new NioDirectCoder(size);
+ return new NioDirectCoder(size, false);
+ }
+ },
+ NIO_DIRECT_UNSAFE() {
+ @Override
+ Coder newCoder(int size) {
+ return new NioDirectCoder(size, true);
}
},
STREAM() {
@@ -389,6 +398,7 @@ public class CodedOutputStreamTest extends TestCase {
!= CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR));
coder.stream().writeStringNoTag(string);
+ coder.stream().flush();
int stringSize = CodedOutputStream.computeStringSizeNoTag(string);
// Verify that the total bytes written is correct
@@ -478,11 +488,12 @@ public class CodedOutputStreamTest extends TestCase {
public void testWriteByteArrayWithOffsets() throws Exception {
byte[] fullArray = bytes(0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88);
- byte[] destination = new byte[4];
- CodedOutputStream codedStream = CodedOutputStream.newInstance(destination);
- codedStream.writeByteArrayNoTag(fullArray, 2, 2);
- assertEqualBytes(OutputType.ARRAY, bytes(0x02, 0x33, 0x44, 0x00), destination);
- assertEquals(3, codedStream.getTotalBytesWritten());
+ for (OutputType type : new OutputType[] {OutputType.ARRAY}) {
+ Coder coder = type.newCoder(4);
+ coder.stream().writeByteArrayNoTag(fullArray, 2, 2);
+ assertEqualBytes(type, bytes(0x02, 0x33, 0x44), coder.toByteArray());
+ assertEquals(3, coder.stream().getTotalBytesWritten());
+ }
}
public void testSerializeUtf8_MultipleSmallWrites() throws Exception {
@@ -561,7 +572,12 @@ public class CodedOutputStreamTest extends 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 (OutputType outputType :
- new OutputType[] {OutputType.ARRAY, OutputType.NIO_HEAP, OutputType.NIO_DIRECT}) {
+ new OutputType[] {
+ OutputType.ARRAY,
+ OutputType.NIO_HEAP,
+ OutputType.NIO_DIRECT_SAFE,
+ OutputType.NIO_DIRECT_UNSAFE
+ }) {
for (int i = 0; i < 11; i++) {
Coder coder = outputType.newCoder(i);
try {
@@ -599,10 +615,13 @@ public class CodedOutputStreamTest extends TestCase {
public void testNioEncodersWithInitialOffsets() throws Exception {
String value = "abc";
- for (Coder coder : new Coder[] {new NioHeapCoder(10, 2), new NioDirectCoder(10, 2)}) {
+ for (Coder coder :
+ new Coder[] {
+ new NioHeapCoder(10, 2), new NioDirectCoder(10, 2, false), new NioDirectCoder(10, 2, true)
+ }) {
coder.stream().writeStringNoTag(value);
coder.stream().flush();
- assertEqualBytes(coder.getOutputType(), new byte[]{3, 'a', 'b', 'c'}, coder.toByteArray());
+ assertEqualBytes(coder.getOutputType(), new byte[] {3, 'a', 'b', 'c'}, coder.toByteArray());
}
}
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 ce85ae2e..2c272a73 100644
--- a/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DeprecatedFieldTest.java
@@ -31,11 +31,9 @@
package com.google.protobuf;
import protobuf_unittest.UnittestProto.TestDeprecatedFields;
-
-import junit.framework.TestCase;
-
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
+import junit.framework.TestCase;
/**
* Test field deprecation
diff --git a/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java b/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java
index b3302441..b60cd620 100644
--- a/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DescriptorsTest.java
@@ -55,15 +55,15 @@ import protobuf_unittest.UnittestProto.ForeignMessage;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
+import protobuf_unittest.UnittestProto.TestJsonName;
import protobuf_unittest.UnittestProto.TestMultipleExtensionRanges;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestReservedFields;
import protobuf_unittest.UnittestProto.TestService;
-import junit.framework.TestCase;
-
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import junit.framework.TestCase;
/**
* Unit test for {@link Descriptors}.
@@ -805,4 +805,15 @@ public class DescriptorsTest extends TestCase {
Descriptors.FileDescriptor.buildFrom(
fileDescriptorProto, new FileDescriptor[0]);
}
+
+ public void testFieldJsonName() throws Exception {
+ Descriptor d = TestJsonName.getDescriptor();
+ assertEquals(6, d.getFields().size());
+ assertEquals("fieldName1", d.getFields().get(0).getJsonName());
+ assertEquals("fieldName2", d.getFields().get(1).getJsonName());
+ assertEquals("FieldName3", d.getFields().get(2).getJsonName());
+ assertEquals("FieldName4", d.getFields().get(3).getJsonName());
+ assertEquals("FIELDNAME5", d.getFields().get(4).getJsonName());
+ assertEquals("@type", d.getFields().get(5).getJsonName());
+ }
}
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 8e8e4fe2..d8942792 100644
--- a/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DoubleArrayListTest.java
@@ -32,11 +32,10 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
+import junit.framework.TestCase;
/**
* Tests for {@link DoubleArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
index 8f3a74c1..77d14f6b 100644
--- a/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
@@ -37,10 +37,8 @@ import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestPackedTypes;
-
-import junit.framework.TestCase;
-
import java.util.Arrays;
+import junit.framework.TestCase;
/**
* Unit test for {@link DynamicMessage}. See also {@link MessageTest}, which
diff --git a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
index c1246782..6157e589 100644
--- a/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
@@ -32,26 +32,24 @@ package com.google.protobuf;
import protobuf_unittest.NonNestedExtension;
import protobuf_unittest.NonNestedExtensionLite;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
/**
* Tests for {@link ExtensionRegistryFactory} and the {@link ExtensionRegistry} instances it
* creates.
- *
+ *
* <p>This test simulates the runtime behaviour of the ExtensionRegistryFactory by delegating test
* definitions to two inner classes {@link InnerTest} and {@link InnerLiteTest}, the latter of
* which is executed using a custom ClassLoader, simulating the ProtoLite environment.
- *
+ *
* <p>The test mechanism employed here is based on the pattern in
* {@code com.google.common.util.concurrent.AbstractFutureFallbackAtomicHelperTest}
*/
@@ -68,6 +66,7 @@ public class ExtensionRegistryFactoryTest extends TestCase {
void testEmpty();
void testIsFullRegistry();
void testAdd();
+ void testAdd_immutable();
}
/**
@@ -125,6 +124,29 @@ public class ExtensionRegistryFactoryTest extends TestCase {
assertNotNull("Extension is registered in masqueraded full registry",
fullRegistry2.findImmutableExtensionByName("protobuf_unittest.nonNestedExtension"));
}
+
+ @Override
+ public void testAdd_immutable() {
+ ExtensionRegistryLite registry1 = ExtensionRegistryLite.newInstance().getUnmodifiable();
+ try {
+ NonNestedExtensionLite.registerAllExtensions(registry1);
+ fail();
+ } catch (UnsupportedOperationException expected) {}
+ try {
+ registry1.add(NonNestedExtensionLite.nonNestedExtensionLite);
+ fail();
+ } catch (UnsupportedOperationException expected) {}
+
+ ExtensionRegistryLite registry2 = ExtensionRegistryLite.newInstance().getUnmodifiable();
+ try {
+ NonNestedExtension.registerAllExtensions((ExtensionRegistry) registry2);
+ fail();
+ } catch (IllegalArgumentException expected) {}
+ try {
+ registry2.add(NonNestedExtension.nonNestedExtension);
+ fail();
+ } catch (IllegalArgumentException expected) {}
+ }
}
/**
@@ -162,12 +184,21 @@ public class ExtensionRegistryFactoryTest extends TestCase {
NonNestedExtensionLite.MessageLiteToBeExtended.getDefaultInstance(), 1);
assertNotNull("Extension is registered in Lite registry", extension);
}
+
+ @Override
+ public void testAdd_immutable() {
+ ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance().getUnmodifiable();
+ try {
+ NonNestedExtensionLite.registerAllExtensions(registry);
+ fail();
+ } catch (UnsupportedOperationException expected) {}
+ }
}
/**
* Defines a suite of tests which the JUnit3 runner retrieves by reflection.
*/
- public static Test suite() {
+ public static Test suite() {
TestSuite suite = new TestSuite();
for (Method method : RegistryTests.class.getMethods()) {
suite.addTest(TestSuite.createTest(ExtensionRegistryFactoryTest.class, method.getName()));
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 0e13a598..aa36be49 100644
--- a/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/FloatArrayListTest.java
@@ -32,11 +32,10 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
+import junit.framework.TestCase;
/**
* Tests for {@link FloatArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
index 127e06fd..3eece26a 100644
--- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
@@ -65,9 +65,6 @@ import protobuf_unittest.UnittestProto.TestExtremeDefaultValues;
import protobuf_unittest.UnittestProto.TestOneof2;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
@@ -76,6 +73,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import junit.framework.TestCase;
/**
* Unit test for generated messages and generated code. See also
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 e59e3c6e..60c85450 100644
--- a/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/IntArrayListTest.java
@@ -32,11 +32,10 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
+import junit.framework.TestCase;
/**
* Tests for {@link IntArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java
index 8d1de6dc..efdfdfbe 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyFieldLiteTest.java
@@ -35,10 +35,8 @@ import static protobuf_unittest.UnittestProto.optionalInt64Extension;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
-import junit.framework.TestCase;
-
import java.io.IOException;
+import junit.framework.TestCase;
/**
* Unit test for {@link LazyFieldLite}.
diff --git a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
index ce473ae9..5f013f3c 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyFieldTest.java
@@ -32,10 +32,8 @@ package com.google.protobuf;
import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
-
-import junit.framework.TestCase;
-
import java.io.IOException;
+import junit.framework.TestCase;
/**
* Unit test for {@link LazyField}.
diff --git a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
index e5b11cf1..c8ca9b6a 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyMessageLiteTest.java
@@ -34,10 +34,8 @@ import protobuf_unittest.LazyFieldsLite.LazyExtension;
import protobuf_unittest.LazyFieldsLite.LazyInnerMessageLite;
import protobuf_unittest.LazyFieldsLite.LazyMessageLite;
import protobuf_unittest.LazyFieldsLite.LazyNestedInnerMessageLite;
-
-import junit.framework.TestCase;
-
import java.util.ArrayList;
+import junit.framework.TestCase;
/**
* Unit test for messages with lazy fields.
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
index 497c4df2..d2bee2a4 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringArrayListTest.java
@@ -32,13 +32,12 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
+import junit.framework.TestCase;
/**
* Tests for {@link LazyStringArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
index 0ef414aa..006e4933 100644
--- a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
@@ -32,10 +32,8 @@ package com.google.protobuf;
import protobuf_unittest.UnittestProto;
-
-import junit.framework.TestCase;
-
import java.io.IOException;
+import junit.framework.TestCase;
/**
* Tests to make sure the lazy conversion of UTF8-encoded byte arrays to
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 b3a246dc..254beba1 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteTest.java
@@ -35,7 +35,6 @@ import static java.util.Collections.singletonList;
import com.google.protobuf.UnittestImportLite.ImportEnumLite;
import com.google.protobuf.UnittestImportPublicLite.PublicImportMessageLite;
-import com.google.protobuf.UnittestLite;
import com.google.protobuf.UnittestLite.ForeignEnumLite;
import com.google.protobuf.UnittestLite.ForeignMessageLite;
import com.google.protobuf.UnittestLite.TestAllExtensionsLite;
@@ -52,15 +51,8 @@ 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 junit.framework.TestCase;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.NotSerializableException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
/**
* Test lite runtime.
*
@@ -139,7 +131,6 @@ public class LiteTest extends TestCase {
UnittestLite.optionalNestedMessageExtensionLite).getBb());
}
-
public void testClone() {
TestAllTypesLite.Builder expected = TestAllTypesLite.newBuilder()
.setOptionalInt32(123);
diff --git a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
index 2e7792a8..eac47448 100644
--- a/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LiteralByteStringTest.java
@@ -30,8 +30,6 @@
package com.google.protobuf;
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
@@ -45,6 +43,7 @@ import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
+import junit.framework.TestCase;
/**
* Test {@code LiteralByteString} by setting up a reference string in {@link #setUp()}.
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 6aaf85d7..6bbdfcaa 100644
--- a/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/LongArrayListTest.java
@@ -32,11 +32,10 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
+import junit.framework.TestCase;
/**
* Tests for {@link LongArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
index 04d58006..8b64fa27 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
@@ -35,15 +35,13 @@ import map_lite_test.MapForProto2TestProto.TestMap;
import map_lite_test.MapForProto2TestProto.TestMap.MessageValue;
import map_lite_test.MapForProto2TestProto.TestMapOrBuilder;
import map_lite_test.MapForProto2TestProto.TestUnknownEnumValue;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
+import junit.framework.TestCase;
/**
* Unit tests for map fields.
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 e8246bf6..76bd7bd9 100644
--- a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
+++ b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
@@ -32,14 +32,14 @@ package com.google.protobuf;
import com.google.protobuf.Descriptors.FieldDescriptor;
import map_test.MapForProto2TestProto.BizarroTestMap;
+import map_test.MapForProto2TestProto.ReservedAsMapField;
+import map_test.MapForProto2TestProto.ReservedAsMapFieldWithEnumValue;
import map_test.MapForProto2TestProto.TestMap;
import map_test.MapForProto2TestProto.TestMap.MessageValue;
import map_test.MapForProto2TestProto.TestMap.MessageWithRequiredFields;
import map_test.MapForProto2TestProto.TestMapOrBuilder;
import map_test.MapForProto2TestProto.TestRecursiveMap;
import map_test.MapForProto2TestProto.TestUnknownEnumValue;
-import junit.framework.TestCase;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
@@ -47,6 +47,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import junit.framework.TestCase;
/**
* Unit tests for map fields in proto2 protos.
@@ -1143,6 +1144,11 @@ public class MapForProto2Test extends TestCase {
assertEquals(2, mapEntry.getAllFields().size());
}
+ public void testReservedWordsFieldNames() {
+ ReservedAsMapField.newBuilder().build();
+ ReservedAsMapFieldWithEnumValue.newBuilder().build();
+ }
+
private static <K, V> Map<K, V> newMap(K key1, V value1) {
Map<K, V> map = new HashMap<K, V>();
map.put(key1, value1);
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 caef246b..035a8335 100644
--- a/java/core/src/test/java/com/google/protobuf/MapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MapTest.java
@@ -36,12 +36,12 @@ import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import map_test.MapTestProto.BizarroTestMap;
+import map_test.MapTestProto.ReservedAsMapField;
+import map_test.MapTestProto.ReservedAsMapFieldWithEnumValue;
import map_test.MapTestProto.TestMap;
import map_test.MapTestProto.TestMap.MessageValue;
import map_test.MapTestProto.TestMapOrBuilder;
import map_test.MapTestProto.TestOnChangeEventPropagation;
-import junit.framework.TestCase;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
@@ -49,6 +49,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import junit.framework.TestCase;
/**
* Unit tests for map fields.
@@ -1307,6 +1308,171 @@ public class MapTest extends TestCase {
}
}
+ public void testReservedWordsFieldNames() {
+ ReservedAsMapField.newBuilder().build();
+ ReservedAsMapFieldWithEnumValue.newBuilder().build();
+ }
+
+ public void testDeterministicSerialziation() throws Exception {
+ TestMap.Builder builder = TestMap.newBuilder();
+ // int32->int32
+ builder.putInt32ToInt32Field(5, 1);
+ builder.putInt32ToInt32Field(1, 1);
+ builder.putInt32ToInt32Field(4, 1);
+ builder.putInt32ToInt32Field(-2, 1);
+ builder.putInt32ToInt32Field(0, 1);
+
+ // uint32->int32
+ builder.putUint32ToInt32Field(5, 1);
+ builder.putUint32ToInt32Field(1, 1);
+ builder.putUint32ToInt32Field(4, 1);
+ builder.putUint32ToInt32Field(-2, 1);
+ builder.putUint32ToInt32Field(0, 1);
+
+ // int64->int32
+ builder.putInt64ToInt32Field(5L, 1);
+ builder.putInt64ToInt32Field(1L, 1);
+ builder.putInt64ToInt32Field(4L, 1);
+ builder.putInt64ToInt32Field(-2L, 1);
+ builder.putInt64ToInt32Field(0L, 1);
+
+ // string->int32
+ builder.putStringToInt32Field("baz", 1);
+ builder.putStringToInt32Field("foo", 1);
+ builder.putStringToInt32Field("bar", 1);
+ builder.putStringToInt32Field("", 1);
+ builder.putStringToInt32Field("hello", 1);
+ builder.putStringToInt32Field("world", 1);
+
+ TestMap message = builder.build();
+ byte[] serialized = new byte[message.getSerializedSize()];
+ CodedOutputStream output = CodedOutputStream.newInstance(serialized);
+ output.useDeterministicSerialization();
+ message.writeTo(output);
+ output.flush();
+
+ CodedInputStream input = CodedInputStream.newInstance(serialized);
+ List<Integer> int32Keys = new ArrayList<Integer>();
+ List<Integer> uint32Keys = new ArrayList<Integer>();
+ List<Long> int64Keys = new ArrayList<Long>();
+ List<String> stringKeys = new ArrayList<String>();
+ int tag;
+ while (true) {
+ tag = input.readTag();
+ if (tag == 0) {
+ break;
+ }
+ int length = input.readRawVarint32();
+ int oldLimit = input.pushLimit(length);
+ switch (WireFormat.getTagFieldNumber(tag)) {
+ case TestMap.STRING_TO_INT32_FIELD_FIELD_NUMBER:
+ stringKeys.add(readMapStringKey(input));
+ break;
+ case TestMap.INT32_TO_INT32_FIELD_FIELD_NUMBER:
+ int32Keys.add(readMapIntegerKey(input));
+ break;
+ case TestMap.UINT32_TO_INT32_FIELD_FIELD_NUMBER:
+ uint32Keys.add(readMapIntegerKey(input));
+ break;
+ case TestMap.INT64_TO_INT32_FIELD_FIELD_NUMBER:
+ int64Keys.add(readMapLongKey(input));
+ break;
+ default:
+ fail("Unexpected fields.");
+ }
+ input.popLimit(oldLimit);
+ }
+ assertEquals(
+ Arrays.asList(-2, 0, 1, 4, 5),
+ int32Keys);
+ assertEquals(
+ Arrays.asList(-2, 0, 1, 4, 5),
+ uint32Keys);
+ assertEquals(
+ Arrays.asList(-2L, 0L, 1L, 4L, 5L),
+ int64Keys);
+ assertEquals(
+ Arrays.asList("", "bar", "baz", "foo", "hello", "world"),
+ stringKeys);
+ }
+
+ public void testInitFromPartialDynamicMessage() {
+ FieldDescriptor fieldDescriptor =
+ TestMap.getDescriptor().findFieldByNumber(TestMap.INT32_TO_MESSAGE_FIELD_FIELD_NUMBER);
+ Descriptor mapEntryType = fieldDescriptor.getMessageType();
+ FieldDescriptor keyField = mapEntryType.findFieldByNumber(1);
+ FieldDescriptor valueField = mapEntryType.findFieldByNumber(2);
+ DynamicMessage dynamicMessage =
+ DynamicMessage.newBuilder(TestMap.getDescriptor())
+ .addRepeatedField(
+ fieldDescriptor,
+ DynamicMessage.newBuilder(mapEntryType)
+ .setField(keyField, 10)
+ .setField(valueField, TestMap.MessageValue.newBuilder().setValue(10).build())
+ .build())
+ .build();
+ TestMap message = TestMap.newBuilder().mergeFrom(dynamicMessage).build();
+ assertEquals(
+ TestMap.MessageValue.newBuilder().setValue(10).build(),
+ message.getInt32ToMessageFieldMap().get(10));
+ }
+
+ public void testInitFromFullyDynamicMessage() {
+ FieldDescriptor fieldDescriptor =
+ TestMap.getDescriptor().findFieldByNumber(TestMap.INT32_TO_MESSAGE_FIELD_FIELD_NUMBER);
+ Descriptor mapEntryType = fieldDescriptor.getMessageType();
+ FieldDescriptor keyField = mapEntryType.findFieldByNumber(1);
+ FieldDescriptor valueField = mapEntryType.findFieldByNumber(2);
+ DynamicMessage dynamicMessage =
+ DynamicMessage.newBuilder(TestMap.getDescriptor())
+ .addRepeatedField(
+ fieldDescriptor,
+ DynamicMessage.newBuilder(mapEntryType)
+ .setField(keyField, 10)
+ .setField(
+ valueField,
+ DynamicMessage.newBuilder(TestMap.MessageValue.getDescriptor())
+ .setField(
+ TestMap.MessageValue.getDescriptor().findFieldByName("value"), 10)
+ .build())
+ .build())
+ .build();
+ TestMap message = TestMap.newBuilder().mergeFrom(dynamicMessage).build();
+ assertEquals(
+ TestMap.MessageValue.newBuilder().setValue(10).build(),
+ message.getInt32ToMessageFieldMap().get(10));
+ }
+
+ private int readMapIntegerKey(CodedInputStream input) throws IOException {
+ int tag = input.readTag();
+ assertEquals(WireFormat.makeTag(1, WireFormat.WIRETYPE_VARINT), tag);
+ int ret = input.readInt32();
+ // skip the value field.
+ input.skipField(input.readTag());
+ assertTrue(input.isAtEnd());
+ return ret;
+ }
+
+ private long readMapLongKey(CodedInputStream input) throws IOException {
+ int tag = input.readTag();
+ assertEquals(WireFormat.makeTag(1, WireFormat.WIRETYPE_VARINT), tag);
+ long ret = input.readInt64();
+ // skip the value field.
+ input.skipField(input.readTag());
+ assertTrue(input.isAtEnd());
+ return ret;
+ }
+
+ private String readMapStringKey(CodedInputStream input) throws IOException {
+ int tag = input.readTag();
+ assertEquals(WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED), tag);
+ String ret = input.readString();
+ // skip the value field.
+ input.skipField(input.readTag());
+ assertTrue(input.isAtEnd());
+ return ret;
+ }
+
private static <K, V> Map<K, V> newMap(K key1, V value1) {
Map<K, V> map = new HashMap<K, V>();
map.put(key1, value1);
diff --git a/java/core/src/test/java/com/google/protobuf/MessageTest.java b/java/core/src/test/java/com/google/protobuf/MessageTest.java
index dcd1aba7..75b79a34 100644
--- a/java/core/src/test/java/com/google/protobuf/MessageTest.java
+++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java
@@ -35,10 +35,8 @@ import protobuf_unittest.UnittestProto.TestAllExtensions;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestRequired;
import protobuf_unittest.UnittestProto.TestRequiredForeign;
-
-import junit.framework.TestCase;
-
import java.util.List;
+import junit.framework.TestCase;
/**
* Misc. unit tests for message operations that apply to both generated
diff --git a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
index 542e28c0..03ed65a5 100644
--- a/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NestedBuildersTest.java
@@ -32,11 +32,9 @@ package com.google.protobuf;
import protobuf_unittest.Vehicle;
import protobuf_unittest.Wheel;
-
-import junit.framework.TestCase;
-
import java.util.ArrayList;
import java.util.List;
+import junit.framework.TestCase;
/**
* Test cases that exercise end-to-end use cases involving
diff --git a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
index 6be5b93c..c388bd05 100644
--- a/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
+++ b/java/core/src/test/java/com/google/protobuf/NioByteStringTest.java
@@ -32,8 +32,6 @@ package com.google.protobuf;
import static com.google.protobuf.Internal.UTF_8;
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
@@ -48,6 +46,7 @@ import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
+import junit.framework.TestCase;
/**
* Tests for {@link NioByteString}.
diff --git a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
index bf1f1d71..e376b1cd 100644
--- a/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ParseExceptionsTest.java
@@ -36,16 +36,14 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
/**
* Tests the exceptions thrown when parsing from a stream. The methods on the {@link Parser}
diff --git a/java/core/src/test/java/com/google/protobuf/ParserTest.java b/java/core/src/test/java/com/google/protobuf/ParserTest.java
index 30842d2c..7086912b 100644
--- a/java/core/src/test/java/com/google/protobuf/ParserTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ParserTest.java
@@ -42,13 +42,11 @@ import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestParsingMerge;
import protobuf_unittest.UnittestProto.TestRequired;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import junit.framework.TestCase;
/**
* Unit test for {@link Parser}.
diff --git a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
index 3f45e226..af717bfd 100644
--- a/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ProtobufArrayListTest.java
@@ -32,12 +32,11 @@ package com.google.protobuf;
import static java.util.Arrays.asList;
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
+import junit.framework.TestCase;
/**
* Tests for {@link ProtobufArrayList}.
diff --git a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
index 241a4354..edbd0afd 100644
--- a/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
+++ b/java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
@@ -32,11 +32,9 @@ package com.google.protobuf;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestAllTypesOrBuilder;
-
-import junit.framework.TestCase;
-
import java.util.Collections;
import java.util.List;
+import junit.framework.TestCase;
/**
* Tests for {@link RepeatedFieldBuilderV3}. This tests basic functionality.
diff --git a/java/core/src/test/java/com/google/protobuf/ServiceTest.java b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
index b902737d..b895ad8d 100644
--- a/java/core/src/test/java/com/google/protobuf/ServiceTest.java
+++ b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
@@ -42,15 +42,13 @@ import protobuf_unittest.UnittestProto.FooResponse;
import protobuf_unittest.UnittestProto.TestAllTypes;
import protobuf_unittest.UnittestProto.TestService;
+import java.util.HashSet;
+import java.util.Set;
import junit.framework.TestCase;
-
import org.easymock.classextension.EasyMock;
import org.easymock.IArgumentMatcher;
import org.easymock.classextension.IMocksControl;
-import java.util.HashSet;
-import java.util.Set;
-
/**
* Tests services and stubs.
*
@@ -271,6 +269,8 @@ public class ServiceTest extends TestCase {
file.getServices().get(0).getMethods().get(0).getName());
}
+
+
// =================================================================
/**
diff --git a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
index e96ecd65..a7f8342d 100644
--- a/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
+++ b/java/core/src/test/java/com/google/protobuf/SmallSortedMapTest.java
@@ -30,8 +30,6 @@
package com.google.protobuf;
-import junit.framework.TestCase;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -40,6 +38,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
+import junit.framework.TestCase;
/**
* @author darick@google.com Darick Tong
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 d94f99e3..d4a18a22 100644
--- a/java/core/src/test/java/com/google/protobuf/TestUtil.java
+++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java
@@ -232,12 +232,10 @@ import protobuf_unittest.UnittestProto.TestOneof2;
import protobuf_unittest.UnittestProto.TestPackedExtensions;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import protobuf_unittest.UnittestProto.TestUnpackedTypes;
-
-import junit.framework.Assert;
-
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
+import junit.framework.Assert;
/**
* Contains methods for setting all fields of {@code TestAllTypes} to
@@ -260,6 +258,13 @@ public final class TestUtil {
}
/**
+ * Dirties the message by resetting the momoized serialized size.
+ */
+ public static void resetMemoizedSize(AbstractMessage message) {
+ message.memoizedSize = -1;
+ }
+
+ /**
* Get a {@code TestAllTypes} with all fields set as they would be by
* {@link #setAllFields(TestAllTypes.Builder)}.
*/
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 14783b0a..6a91b02f 100644
--- a/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/TextFormatTest.java
@@ -42,11 +42,9 @@ import protobuf_unittest.UnittestProto.TestAllTypes.NestedMessage;
import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestOneof2;
import proto2_wireformat_unittest.UnittestMsetWireFormat.TestMessageSet;
-
-import junit.framework.TestCase;
-
import java.io.StringReader;
import java.util.List;
+import junit.framework.TestCase;
/**
* Test case for {@link TextFormat}.
@@ -992,10 +990,35 @@ public class TextFormatTest extends TestCase {
assertParseSuccessWithOverwriteForbidden("repeated_nested_message [{ bb: 1 }, { bb: 2 }]\n");
}
+ public void testParseShortRepeatedFormOfEmptyRepeatedFields() throws Exception {
+ assertParseSuccessWithOverwriteForbidden("repeated_foreign_enum: []");
+ assertParseSuccessWithOverwriteForbidden("repeated_int32: []\n");
+ assertParseSuccessWithOverwriteForbidden("RepeatedGroup []\n");
+ assertParseSuccessWithOverwriteForbidden("repeated_nested_message []\n");
+ }
+
+ public void testParseShortRepeatedFormWithTrailingComma() throws Exception {
+ assertParseErrorWithOverwriteForbidden(
+ "1:38: Expected identifier. Found \']\'",
+ "repeated_foreign_enum: [FOREIGN_FOO, ]\n");
+ assertParseErrorWithOverwriteForbidden(
+ "1:22: Couldn't parse integer: For input string: \"]\"",
+ "repeated_int32: [ 1, ]\n");
+ assertParseErrorWithOverwriteForbidden(
+ "1:25: Expected \"{\".",
+ "RepeatedGroup [{ a: 1 },]\n");
+ assertParseErrorWithOverwriteForbidden(
+ "1:37: Expected \"{\".",
+ "repeated_nested_message [{ bb: 1 }, ]\n");
+ }
+
public void testParseShortRepeatedFormOfNonRepeatedFields() throws Exception {
assertParseErrorWithOverwriteForbidden(
"1:17: Couldn't parse integer: For input string: \"[\"",
"optional_int32: [1]\n");
+ assertParseErrorWithOverwriteForbidden(
+ "1:17: Couldn't parse integer: For input string: \"[\"",
+ "optional_int32: []\n");
}
// =======================================================================
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 573cd665..26ea850e 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java
@@ -35,11 +35,9 @@ import com.google.protobuf.UnittestLite.TestAllTypesLite;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Bar;
import protobuf_unittest.lite_equals_and_hash.LiteEqualsAndHash.Foo;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import junit.framework.TestCase;
/**
* Tests for {@link UnknownFieldSetLite}.
diff --git a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
index 32380f70..f81e90b4 100644
--- a/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnknownFieldSetTest.java
@@ -38,11 +38,9 @@ import protobuf_unittest.UnittestProto.TestEmptyMessage;
import protobuf_unittest.UnittestProto.TestEmptyMessageWithExtensions;
import protobuf_unittest.UnittestProto.TestPackedExtensions;
import protobuf_unittest.UnittestProto.TestPackedTypes;
-
-import junit.framework.TestCase;
-
import java.util.Arrays;
import java.util.Map;
+import junit.framework.TestCase;
/**
* Tests related to unknown field handling.
diff --git a/java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java b/java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java
index b1c75fc3..00f201ca 100644
--- a/java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java
+++ b/java/core/src/test/java/com/google/protobuf/UnmodifiableLazyStringListTest.java
@@ -30,11 +30,10 @@
package com.google.protobuf;
-import junit.framework.TestCase;
-
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
+import junit.framework.TestCase;
/**
* Tests for {@link UnmodifiableLazyStringList}.
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 e66b371c..370860c2 100644
--- a/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
+++ b/java/core/src/test/java/com/google/protobuf/WireFormatTest.java
@@ -44,12 +44,10 @@ import protobuf_unittest.UnittestProto.TestOneofBackwardsCompatible;
import protobuf_unittest.UnittestProto.TestPackedExtensions;
import protobuf_unittest.UnittestProto.TestPackedTypes;
import proto2_wireformat_unittest.UnittestMsetWireFormat.TestMessageSet;
-
-import junit.framework.TestCase;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
+import junit.framework.TestCase;
/**
* Tests related to parsing and serialization.
diff --git a/java/core/src/test/proto/com/google/protobuf/field_presence_test.proto b/java/core/src/test/proto/com/google/protobuf/field_presence_test.proto
index 86cdd286..2367bd8b 100644
--- a/java/core/src/test/proto/com/google/protobuf/field_presence_test.proto
+++ b/java/core/src/test/proto/com/google/protobuf/field_presence_test.proto
@@ -36,7 +36,6 @@ import "google/protobuf/unittest.proto";
option java_package = "com.google.protobuf";
option java_outer_classname = "FieldPresenceTestProto";
-option java_generate_equals_and_hash = true;
message TestAllTypes {
enum NestedEnum {
diff --git a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto
index de3336a5..2ca0251c 100644
--- a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto
+++ b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto
@@ -32,7 +32,6 @@ syntax = "proto2";
option java_outer_classname = "MapForProto2TestProto";
-option java_generate_equals_and_hash = true;
message TestMap {
message MessageValue {
@@ -81,6 +80,42 @@ message BizarroTestMap {
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
+}
package map_for_proto2_lite_test;
option java_package = "map_lite_test";
option optimize_for = LITE_RUNTIME;
diff --git a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto
index 0c92b0ae..974f8a2c 100644
--- a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto
+++ b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_test.proto
@@ -34,7 +34,6 @@ package map_for_proto2_test;
option java_package = "map_test";
option java_outer_classname = "MapForProto2TestProto";
-option java_generate_equals_and_hash = true;
message TestMap {
message MessageValue {
@@ -83,3 +82,39 @@ message BizarroTestMap {
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/core/src/test/proto/com/google/protobuf/map_test.proto b/java/core/src/test/proto/com/google/protobuf/map_test.proto
index 9eb63fc3..bc2105e5 100644
--- a/java/core/src/test/proto/com/google/protobuf/map_test.proto
+++ b/java/core/src/test/proto/com/google/protobuf/map_test.proto
@@ -34,7 +34,6 @@ package map_test;
option java_package = "map_test";
option java_outer_classname = "MapTestProto";
-option java_generate_equals_and_hash = true;
message TestMap {
message MessageValue {
@@ -53,6 +52,8 @@ message TestMap {
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
@@ -71,3 +72,39 @@ message BizarroTestMap {
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/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto b/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto
index 2b1f65e4..d2c77936 100644
--- a/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto
+++ b/java/core/src/test/proto/com/google/protobuf/test_bad_identifiers.proto
@@ -43,7 +43,6 @@ package io_protocol_tests;
option java_package = "com.google.protobuf";
option java_outer_classname = "TestBadIdentifiersProto";
-option java_generate_equals_and_hash = true;
message TestMessage {
optional string cached_size = 1;
diff --git a/java/lite/pom.xml b/java/lite/pom.xml
index 9862cd94..d7b15097 100644
--- a/java/lite/pom.xml
+++ b/java/lite/pom.xml
@@ -76,10 +76,38 @@
<!-- 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>
- <generatedSourcesDirectory>${generated.sources.lite.dir}</generatedSourcesDirectory>
- <generatedTestSourcesDirectory>${generated.testsources.lite.dir}</generatedTestSourcesDirectory>
<includes>
<include>**/AbstractMessageLite.java</include>
<include>**/AbstractParser.java</include>
diff --git a/java/pom.xml b/java/pom.xml
index 3a91a0ba..6789e7c1 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -11,7 +11,7 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.0.0</version>
+ <version>3.1.0</version>
<packaging>pom</packaging>
<name>Protocol Buffers [Parent]</name>
@@ -94,7 +94,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
- <version>3.3</version>
+ <version>3.6.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
diff --git a/java/util/pom.xml b/java/util/pom.xml
index 0d5e8e37..0ccfc848 100644
--- a/java/util/pom.xml
+++ b/java/util/pom.xml
@@ -6,7 +6,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
- <version>3.0.0</version>
+ <version>3.1.0</version>
</parent>
<artifactId>protobuf-java-util</artifactId>
@@ -28,7 +28,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
- <version>2.3</version>
+ <version>2.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
@@ -79,12 +79,24 @@
</executions>
</plugin>
+ <!-- Add the generated test sources to the build -->
<plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <!-- Add the generated test sources to the build -->
- <generatedTestSourcesDirectory>${generated.testsources.dir}</generatedTestSourcesDirectory>
- </configuration>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>add-generated-test-sources</id>
+ <phase>generate-test-sources</phase>
+ <goals>
+ <goal>add-test-source</goal>
+ </goals>
+ <configuration>
+ <sources>
+ <source>${generated.testsources.dir}</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
</plugin>
<!-- Configure the OSGI bundle -->
diff --git a/java/util/src/main/java/com/google/protobuf/util/Durations.java b/java/util/src/main/java/com/google/protobuf/util/Durations.java
index 5fe6ebca..9333168d 100644
--- a/java/util/src/main/java/com/google/protobuf/util/Durations.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Durations.java
@@ -30,50 +30,86 @@
package com.google.protobuf.util;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.math.IntMath.checkedAdd;
+import static com.google.common.math.IntMath.checkedSubtract;
+import static com.google.common.math.LongMath.checkedAdd;
+import static com.google.common.math.LongMath.checkedMultiply;
+import static com.google.common.math.LongMath.checkedSubtract;
import static com.google.protobuf.util.Timestamps.MICROS_PER_SECOND;
import static com.google.protobuf.util.Timestamps.MILLIS_PER_SECOND;
import static com.google.protobuf.util.Timestamps.NANOS_PER_MICROSECOND;
import static com.google.protobuf.util.Timestamps.NANOS_PER_MILLISECOND;
import static com.google.protobuf.util.Timestamps.NANOS_PER_SECOND;
+import com.google.common.collect.ComparisonChain;
import com.google.protobuf.Duration;
-
import java.text.ParseException;
+import java.util.Comparator;
/**
- * Utilities to help create/manipulate {@code protobuf/duration.proto}.
+ * Utilities to help create/manipulate {@code protobuf/duration.proto}. All operations throw an
+ * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Duration) valid}.
*/
public final class Durations {
static final long DURATION_SECONDS_MIN = -315576000000L;
static final long DURATION_SECONDS_MAX = 315576000000L;
- // TODO(kak): Do we want to expose Duration constants for MAX/MIN?
+ /** A constant holding the minimum valid {@link Duration}, approximately {@code -10,000} years. */
+ public static final Duration MIN_VALUE =
+ Duration.newBuilder().setSeconds(DURATION_SECONDS_MIN).setNanos(-999999999).build();
+
+ /** A constant holding the maximum valid {@link Duration}, approximately {@code +10,000} years. */
+ public static final Duration MAX_VALUE =
+ Duration.newBuilder().setSeconds(DURATION_SECONDS_MAX).setNanos(999999999).build();
private Durations() {}
+ private static final Comparator<Duration> COMPARATOR =
+ new Comparator<Duration>() {
+ @Override
+ public int compare(Duration d1, Duration d2) {
+ checkValid(d1);
+ checkValid(d2);
+
+ return ComparisonChain.start()
+ .compare(d1.getSeconds(), d2.getSeconds())
+ .compare(d1.getNanos(), d2.getNanos())
+ .result();
+ }
+ };
+
+ /**
+ * Returns a {@link Comparator} for {@link Duration}s which sorts in increasing chronological
+ * order. Nulls and invalid {@link Duration}s are not allowed (see {@link #isValid}).
+ */
+ public static Comparator<Duration> comparator() {
+ return COMPARATOR;
+ }
+
/**
* Returns true if the given {@link Duration} is valid. The {@code seconds} value must be in the
* range [-315,576,000,000, +315,576,000,000]. The {@code nanos} value must be in the range
* [-999,999,999, +999,999,999].
*
- * <p>Note: Durations less than one second are represented with a 0 {@code seconds} field and a
- * positive or negative {@code nanos} field. For durations of one second or more, a non-zero value
- * for the {@code nanos} field must be of the same sign as the {@code seconds} field.
+ * <p><b>Note:</b> Durations less than one second are represented with a 0 {@code seconds} field
+ * and a positive or negative {@code nanos} field. For durations of one second or more, a non-zero
+ * value for the {@code nanos} field must be of the same sign as the {@code seconds} field.
*/
public static boolean isValid(Duration duration) {
return isValid(duration.getSeconds(), duration.getNanos());
}
/**
- * Returns true if the given number of seconds and nanos is a valid {@link Duration}. The
- * {@code seconds} value must be in the range [-315,576,000,000, +315,576,000,000]. The
- * {@code nanos} value must be in the range [-999,999,999, +999,999,999].
+ * Returns true if the given number of seconds and nanos is a valid {@link Duration}. The {@code
+ * seconds} value must be in the range [-315,576,000,000, +315,576,000,000]. The {@code nanos}
+ * value must be in the range [-999,999,999, +999,999,999].
*
- * <p>Note: Durations less than one second are represented with a 0 {@code seconds} field and a
- * positive or negative {@code nanos} field. For durations of one second or more, a non-zero value
- * for the {@code nanos} field must be of the same sign as the {@code seconds} field.
+ * <p><b>Note:</b> Durations less than one second are represented with a 0 {@code seconds} field
+ * and a positive or negative {@code nanos} field. For durations of one second or more, a non-zero
+ * value for the {@code nanos} field must be of the same sign as the {@code seconds} field.
*/
- public static boolean isValid(long seconds, long nanos) {
+ public static boolean isValid(long seconds, int nanos) {
if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) {
return false;
}
@@ -88,35 +124,35 @@ public final class Durations {
return true;
}
- /**
- * Throws an {@link IllegalArgumentException} if the given seconds/nanos are not
- * a valid {@link Duration}.
- */
- private static void checkValid(long seconds, int nanos) {
- if (!isValid(seconds, nanos)) {
- throw new IllegalArgumentException(String.format(
- "Duration is not valid. See proto definition for valid values. "
- + "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000]."
- + "Nanos (%s) must be in range [-999,999,999, +999,999,999]. "
- + "Nanos must have the same sign as seconds", seconds, nanos));
- }
+ /** Throws an {@link IllegalArgumentException} if the given {@link Duration} is not valid. */
+ public static Duration checkValid(Duration duration) {
+ long seconds = duration.getSeconds();
+ int nanos = duration.getNanos();
+ checkArgument(
+ isValid(seconds, nanos),
+ "Duration is not valid. See proto definition for valid values. "
+ + "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000]. "
+ + "Nanos (%s) must be in range [-999,999,999, +999,999,999]. "
+ + "Nanos must have the same sign as seconds",
+ seconds,
+ nanos);
+ return duration;
}
/**
- * Convert Duration to string format. The string format will contains 3, 6,
- * or 9 fractional digits depending on the precision required to represent
- * the exact Duration value. For example: "1s", "1.010s", "1.000000100s",
- * "-3.100s" The range that can be represented by Duration is from
+ * Convert Duration to string format. The string format will contains 3, 6, or 9 fractional digits
+ * depending on the precision required to represent the exact Duration value. For example: "1s",
+ * "1.010s", "1.000000100s", "-3.100s" The range that can be represented by Duration is from
* -315,576,000,000 to +315,576,000,000 inclusive (in seconds).
*
* @return The string representation of the given duration.
- * @throws IllegalArgumentException if the given duration is not in the valid
- * range.
+ * @throws IllegalArgumentException if the given duration is not in the valid range.
*/
public static String toString(Duration duration) {
+ checkValid(duration);
+
long seconds = duration.getSeconds();
int nanos = duration.getNanos();
- checkValid(seconds, nanos);
StringBuilder result = new StringBuilder();
if (seconds < 0 || nanos < 0) {
@@ -172,9 +208,20 @@ public final class Durations {
}
}
+ /** Create a Duration from the number of seconds. */
+ public static Duration fromSeconds(long seconds) {
+ return normalizedDuration(seconds, 0);
+ }
+
/**
- * Create a Duration from the number of milliseconds.
+ * Convert a Duration to the number of seconds. The result will be rounded towards 0 to the
+ * nearest second. E.g., if the duration represents -1 nanosecond, it will be rounded to 0.
*/
+ public static long toSeconds(Duration duration) {
+ return checkValid(duration).getSeconds();
+ }
+
+ /** Create a Duration from the number of milliseconds. */
public static Duration fromMillis(long milliseconds) {
return normalizedDuration(
milliseconds / MILLIS_PER_SECOND,
@@ -182,17 +229,17 @@ public final class Durations {
}
/**
- * Convert a Duration to the number of milliseconds.The result will be
- * rounded towards 0 to the nearest millisecond. E.g., if the duration
- * represents -1 nanosecond, it will be rounded to 0.
+ * Convert a Duration to the number of milliseconds. The result will be rounded towards 0 to the
+ * nearest millisecond. E.g., if the duration represents -1 nanosecond, it will be rounded to 0.
*/
public static long toMillis(Duration duration) {
- return duration.getSeconds() * MILLIS_PER_SECOND + duration.getNanos() / NANOS_PER_MILLISECOND;
+ checkValid(duration);
+ return checkedAdd(
+ checkedMultiply(duration.getSeconds(), MILLIS_PER_SECOND),
+ duration.getNanos() / NANOS_PER_MILLISECOND);
}
- /**
- * Create a Duration from the number of microseconds.
- */
+ /** Create a Duration from the number of microseconds. */
public static Duration fromMicros(long microseconds) {
return normalizedDuration(
microseconds / MICROS_PER_SECOND,
@@ -200,57 +247,60 @@ public final class Durations {
}
/**
- * Convert a Duration to the number of microseconds.The result will be
- * rounded towards 0 to the nearest microseconds. E.g., if the duration
- * represents -1 nanosecond, it will be rounded to 0.
+ * Convert a Duration to the number of microseconds. The result will be rounded towards 0 to the
+ * nearest microseconds. E.g., if the duration represents -1 nanosecond, it will be rounded to 0.
*/
public static long toMicros(Duration duration) {
- return duration.getSeconds() * MICROS_PER_SECOND + duration.getNanos() / NANOS_PER_MICROSECOND;
+ checkValid(duration);
+ return checkedAdd(
+ checkedMultiply(duration.getSeconds(), MICROS_PER_SECOND),
+ duration.getNanos() / NANOS_PER_MICROSECOND);
}
- /**
- * Create a Duration from the number of nanoseconds.
- */
+ /** Create a Duration from the number of nanoseconds. */
public static Duration fromNanos(long nanoseconds) {
return normalizedDuration(
nanoseconds / NANOS_PER_SECOND, (int) (nanoseconds % NANOS_PER_SECOND));
}
- /**
- * Convert a Duration to the number of nanoseconds.
- */
+ /** Convert a Duration to the number of nanoseconds. */
public static long toNanos(Duration duration) {
- return duration.getSeconds() * NANOS_PER_SECOND + duration.getNanos();
+ checkValid(duration);
+ return checkedAdd(
+ checkedMultiply(duration.getSeconds(), NANOS_PER_SECOND), duration.getNanos());
}
- /**
- * Add two durations.
- */
+ /** Add two durations. */
public static Duration add(Duration d1, Duration d2) {
- return normalizedDuration(d1.getSeconds() + d2.getSeconds(), d1.getNanos() + d2.getNanos());
+ checkValid(d1);
+ checkValid(d2);
+ return normalizedDuration(
+ checkedAdd(d1.getSeconds(), d2.getSeconds()), checkedAdd(d1.getNanos(), d2.getNanos()));
}
- /**
- * Subtract a duration from another.
- */
+ /** Subtract a duration from another. */
public static Duration subtract(Duration d1, Duration d2) {
- return normalizedDuration(d1.getSeconds() - d2.getSeconds(), d1.getNanos() - d2.getNanos());
+ checkValid(d1);
+ checkValid(d2);
+ return normalizedDuration(
+ checkedSubtract(d1.getSeconds(), d2.getSeconds()),
+ checkedSubtract(d1.getNanos(), d2.getNanos()));
}
static Duration normalizedDuration(long seconds, int nanos) {
if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
- seconds += nanos / NANOS_PER_SECOND;
+ seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
nanos %= NANOS_PER_SECOND;
}
if (seconds > 0 && nanos < 0) {
- nanos += NANOS_PER_SECOND;
- seconds -= 1;
+ nanos += NANOS_PER_SECOND; // no overflow since nanos is negative (and we're adding)
+ seconds--; // no overflow since seconds is positive (and we're decrementing)
}
if (seconds < 0 && nanos > 0) {
- nanos -= NANOS_PER_SECOND;
- seconds += 1;
+ nanos -= NANOS_PER_SECOND; // no overflow since nanos is positive (and we're subtracting)
+ seconds++; // no overflow since seconds is negative (and we're incrementing)
}
- checkValid(seconds, nanos);
- return Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
+ Duration duration = Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
+ return checkValid(duration);
}
}
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 ad50cc0e..6361b4ac 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
@@ -224,7 +224,7 @@ public class JsonFormat {
* Creates a {@link Parser} with default configuration.
*/
public static Parser parser() {
- return new Parser(TypeRegistry.getEmptyTypeRegistry());
+ return new Parser(TypeRegistry.getEmptyTypeRegistry(), false);
}
/**
@@ -232,9 +232,11 @@ public class JsonFormat {
*/
public static class Parser {
private final TypeRegistry registry;
+ private final boolean ignoringUnknownFields;
- private Parser(TypeRegistry registry) {
+ private Parser(TypeRegistry registry, boolean ignoreUnknownFields) {
this.registry = registry;
+ this.ignoringUnknownFields = ignoreUnknownFields;
}
/**
@@ -247,7 +249,16 @@ public class JsonFormat {
if (this.registry != TypeRegistry.getEmptyTypeRegistry()) {
throw new IllegalArgumentException("Only one registry is allowed.");
}
- return new Parser(registry);
+ return new Parser(registry, this.ignoringUnknownFields);
+ }
+
+ /**
+ * Creates a new {@link Parser} configured to not throw an exception
+ * when an unknown field is encountered. The new Parser clones all other
+ * configurations from this Parser.
+ */
+ public Parser ignoringUnknownFields() {
+ return new Parser(this.registry, true);
}
/**
@@ -259,7 +270,7 @@ public class JsonFormat {
public void merge(String json, Message.Builder builder) throws InvalidProtocolBufferException {
// TODO(xiaofeng): Investigate the allocation overhead and optimize for
// mobile.
- new ParserImpl(registry).merge(json, builder);
+ new ParserImpl(registry, ignoringUnknownFields).merge(json, builder);
}
/**
@@ -272,7 +283,7 @@ public class JsonFormat {
public void merge(Reader json, Message.Builder builder) throws IOException {
// TODO(xiaofeng): Investigate the allocation overhead and optimize for
// mobile.
- new ParserImpl(registry).merge(json, builder);
+ new ParserImpl(registry, ignoringUnknownFields).merge(json, builder);
}
}
@@ -629,6 +640,10 @@ public class JsonFormat {
/** Prints google.protobuf.Any */
private void printAny(MessageOrBuilder message) throws IOException {
+ if (Any.getDefaultInstance().equals(message)) {
+ generator.print("{}");
+ return;
+ }
Descriptor descriptor = message.getDescriptorForType();
FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url");
FieldDescriptor valueField = descriptor.findFieldByName("value");
@@ -1024,9 +1039,11 @@ public class JsonFormat {
private static class ParserImpl {
private final TypeRegistry registry;
private final JsonParser jsonParser;
+ private final boolean ignoringUnknownFields;
- ParserImpl(TypeRegistry registry) {
+ ParserImpl(TypeRegistry registry, boolean ignoreUnknownFields) {
this.registry = registry;
+ this.ignoringUnknownFields = ignoreUnknownFields;
this.jsonParser = new JsonParser();
}
@@ -1191,6 +1208,9 @@ public class JsonFormat {
}
FieldDescriptor field = fieldNameMap.get(entry.getKey());
if (field == null) {
+ if (ignoringUnknownFields) {
+ continue;
+ }
throw new InvalidProtocolBufferException(
"Cannot find field: "
+ entry.getKey()
@@ -1219,6 +1239,9 @@ public class JsonFormat {
throw new InvalidProtocolBufferException("Expect message object but got: " + json);
}
JsonObject object = (JsonObject) json;
+ if (object.entrySet().isEmpty()) {
+ return; // builder never modified, so it will end up building the default instance of Any
+ }
JsonElement typeUrlElement = object.get("@type");
if (typeUrlElement == null) {
throw new InvalidProtocolBufferException("Missing type url when parsing: " + json);
@@ -1311,6 +1334,9 @@ public class JsonFormat {
Message.Builder listBuilder = builder.newBuilderForField(field);
merge(json, listBuilder);
builder.setField(field, listBuilder.build());
+ } else if (json instanceof JsonNull) {
+ builder.setField(
+ type.findFieldByName("null_value"), NullValue.NULL_VALUE.getValueDescriptor());
} else {
throw new IllegalStateException("Unexpected json data: " + json);
}
@@ -1604,11 +1630,6 @@ public class JsonFormat {
}
private ByteString parseBytes(JsonElement json) throws InvalidProtocolBufferException {
- String encoded = json.getAsString();
- if (encoded.length() % 4 != 0) {
- throw new InvalidProtocolBufferException(
- "Bytes field is not encoded in standard BASE64 with paddings: " + encoded);
- }
return ByteString.copyFrom(BaseEncoding.base64().decode(json.getAsString()));
}
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 f1f202da..52b1ab98 100644
--- a/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
+++ b/java/util/src/main/java/com/google/protobuf/util/Timestamps.java
@@ -30,19 +30,29 @@
package com.google.protobuf.util;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.math.IntMath.checkedAdd;
+import static com.google.common.math.IntMath.checkedSubtract;
+import static com.google.common.math.LongMath.checkedAdd;
+import static com.google.common.math.LongMath.checkedMultiply;
+import static com.google.common.math.LongMath.checkedSubtract;
+
+import com.google.common.collect.ComparisonChain;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
-
import java.text.ParseException;
import java.text.SimpleDateFormat;
+import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
- * Utilities to help create/manipulate {@code protobuf/timestamp.proto}.
+ * Utilities to help create/manipulate {@code protobuf/timestamp.proto}. All operations throw an
+ * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Timestamp) valid}.
*/
public final class Timestamps {
+
// Timestamp for "0001-01-01T00:00:00Z"
static final long TIMESTAMP_SECONDS_MIN = -62135596800L;
@@ -55,10 +65,19 @@ public final class Timestamps {
static final long MILLIS_PER_SECOND = 1000;
static final long MICROS_PER_SECOND = 1000000;
- // TODO(kak): Do we want to expose Timestamp constants for MAX/MIN?
+ /** A constant holding the minimum valid {@link Timestamp}, {@code 0001-01-01T00:00:00Z}. */
+ public static final Timestamp MIN_VALUE =
+ Timestamp.newBuilder().setSeconds(TIMESTAMP_SECONDS_MIN).setNanos(0).build();
+
+ /**
+ * A constant holding the maximum valid {@link Timestamp}, {@code 9999-12-31T23:59:59.999999999Z}.
+ */
+ public static final Timestamp MAX_VALUE =
+ Timestamp.newBuilder().setSeconds(TIMESTAMP_SECONDS_MAX).setNanos(999999999).build();
private static final ThreadLocal<SimpleDateFormat> timestampFormat =
new ThreadLocal<SimpleDateFormat>() {
+ @Override
protected SimpleDateFormat initialValue() {
return createTimestampFormat();
}
@@ -76,28 +95,50 @@ public final class Timestamps {
private Timestamps() {}
+ private static final Comparator<Timestamp> COMPARATOR =
+ new Comparator<Timestamp>() {
+ @Override
+ public int compare(Timestamp t1, Timestamp t2) {
+ checkValid(t1);
+ checkValid(t2);
+
+ return ComparisonChain.start()
+ .compare(t1.getSeconds(), t2.getSeconds())
+ .compare(t1.getNanos(), t2.getNanos())
+ .result();
+ }
+ };
+
+ /**
+ * Returns a {@link Comparator} for {@link Timestamp}s which sorts in increasing chronological
+ * order. Nulls and invalid {@link Timestamp}s are not allowed (see {@link #isValid}).
+ */
+ public static Comparator<Timestamp> comparator() {
+ return COMPARATOR;
+ }
+
/**
* Returns true if the given {@link Timestamp} is valid. The {@code seconds} value must be in the
* range [-62,135,596,800, +253,402,300,799] (i.e., between 0001-01-01T00:00:00Z and
* 9999-12-31T23:59:59Z). The {@code nanos} value must be in the range [0, +999,999,999].
*
- * <p>Note: Negative second values with fractions must still have non-negative nanos value that
- * counts forward in time.
+ * <p><b>Note:</b> Negative second values with fractional seconds must still have non-negative
+ * nanos values that count forward in time.
*/
public static boolean isValid(Timestamp timestamp) {
return isValid(timestamp.getSeconds(), timestamp.getNanos());
}
/**
- * Returns true if the given number of seconds and nanos is a valid {@link Timestamp}. The
- * {@code seconds} value must be in the range [-62,135,596,800, +253,402,300,799] (i.e., between
+ * Returns true if the given number of seconds and nanos is a valid {@link Timestamp}. The {@code
+ * seconds} value must be in the range [-62,135,596,800, +253,402,300,799] (i.e., between
* 0001-01-01T00:00:00Z and 9999-12-31T23:59:59Z). The {@code nanos} value must be in the range
* [0, +999,999,999].
*
- * <p>Note: Negative second values with fractions must still have non-negative nanos value that
- * counts forward in time.
+ * <p><b>Note:</b> Negative second values with fractional seconds must still have non-negative
+ * nanos values that count forward in time.
*/
- public static boolean isValid(long seconds, long nanos) {
+ public static boolean isValid(long seconds, int nanos) {
if (seconds < TIMESTAMP_SECONDS_MIN || seconds > TIMESTAMP_SECONDS_MAX) {
return false;
}
@@ -107,37 +148,37 @@ public final class Timestamps {
return true;
}
- /**
- * Throws an {@link IllegalArgumentException} if the given seconds/nanos are not
- * a valid {@link Timestamp}.
- */
- private static void checkValid(long seconds, int nanos) {
- if (!isValid(seconds, nanos)) {
- throw new IllegalArgumentException(String.format(
- "Timestamp is not valid. See proto definition for valid values. "
- + "Seconds (%s) must be in range [-62,135,596,800, +253,402,300,799]."
- + "Nanos (%s) must be in range [0, +999,999,999].",
- seconds, nanos));
- }
+ /** Throws an {@link IllegalArgumentException} if the given {@link Timestamp} is not valid. */
+ public static Timestamp checkValid(Timestamp timestamp) {
+ long seconds = timestamp.getSeconds();
+ int nanos = timestamp.getNanos();
+ checkArgument(
+ isValid(seconds, nanos),
+ "Timestamp is not valid. See proto definition for valid values. "
+ + "Seconds (%s) must be in range [-62,135,596,800, +253,402,300,799]. "
+ + "Nanos (%s) must be in range [0, +999,999,999].",
+ seconds,
+ nanos);
+ return timestamp;
}
/**
- * Convert Timestamp to RFC 3339 date string format. The output will always
- * be Z-normalized and uses 3, 6 or 9 fractional digits as required to
- * represent the exact value. Note that Timestamp can only represent time
- * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. See
+ * Convert Timestamp to RFC 3339 date string format. The output will always be Z-normalized and
+ * uses 3, 6 or 9 fractional digits as required to represent the exact value. Note that Timestamp
+ * can only represent time from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. See
* https://www.ietf.org/rfc/rfc3339.txt
*
* <p>Example of generated format: "1972-01-01T10:00:20.021Z"
*
* @return The string representation of the given timestamp.
- * @throws IllegalArgumentException if the given timestamp is not in the
- * valid range.
+ * @throws IllegalArgumentException if the given timestamp is not in the valid range.
*/
public static String toString(Timestamp timestamp) {
+ checkValid(timestamp);
+
long seconds = timestamp.getSeconds();
int nanos = timestamp.getNanos();
- checkValid(seconds, nanos);
+
StringBuilder result = new StringBuilder();
// Format the seconds part.
Date date = new Date(seconds * MILLIS_PER_SECOND);
@@ -152,10 +193,9 @@ public final class Timestamps {
}
/**
- * Parse from RFC 3339 date string to Timestamp. This method accepts all
- * outputs of {@link #toString(Timestamp)} and it also accepts any fractional
- * digits (or none) and any offset as long as they fit into nano-seconds
- * precision.
+ * Parse from RFC 3339 date string to Timestamp. This method accepts all outputs of {@link
+ * #toString(Timestamp)} and it also accepts any fractional digits (or none) and any offset as
+ * long as they fit into nano-seconds precision.
*
* <p>Example of accepted format: "1972-01-01T10:00:20.021-05:00"
*
@@ -210,13 +250,26 @@ public final class Timestamps {
try {
return normalizedTimestamp(seconds, nanos);
} catch (IllegalArgumentException e) {
- throw new ParseException("Failed to parse timestmap: timestamp is out of range.", 0);
+ throw new ParseException("Failed to parse timestamp: timestamp is out of range.", 0);
}
}
+ /** Create a Timestamp from the number of seconds elapsed from the epoch. */
+ public static Timestamp fromSeconds(long seconds) {
+ return normalizedTimestamp(seconds, 0);
+ }
+
/**
- * Create a Timestamp from the number of milliseconds elapsed from the epoch.
+ * Convert a Timestamp to the number of seconds elapsed from the epoch.
+ *
+ * <p>The result will be rounded down to the nearest second. E.g., if the timestamp represents
+ * "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 second.
*/
+ public static long toSeconds(Timestamp timestamp) {
+ return checkValid(timestamp).getSeconds();
+ }
+
+ /** Create a Timestamp from the number of milliseconds elapsed from the epoch. */
public static Timestamp fromMillis(long milliseconds) {
return normalizedTimestamp(
milliseconds / MILLIS_PER_SECOND,
@@ -226,18 +279,17 @@ public final class Timestamps {
/**
* Convert a Timestamp to the number of milliseconds elapsed from the epoch.
*
- * <p>The result will be rounded down to the nearest millisecond. E.g., if the
- * timestamp represents "1969-12-31T23:59:59.999999999Z", it will be rounded
- * to -1 millisecond.
+ * <p>The result will be rounded down to the nearest millisecond. E.g., if the timestamp
+ * represents "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 millisecond.
*/
public static long toMillis(Timestamp timestamp) {
- return timestamp.getSeconds() * MILLIS_PER_SECOND
- + timestamp.getNanos() / NANOS_PER_MILLISECOND;
+ checkValid(timestamp);
+ return checkedAdd(
+ checkedMultiply(timestamp.getSeconds(), MILLIS_PER_SECOND),
+ timestamp.getNanos() / NANOS_PER_MILLISECOND);
}
- /**
- * Create a Timestamp from the number of microseconds elapsed from the epoch.
- */
+ /** Create a Timestamp from the number of microseconds elapsed from the epoch. */
public static Timestamp fromMicros(long microseconds) {
return normalizedTimestamp(
microseconds / MICROS_PER_SECOND,
@@ -247,65 +299,67 @@ public final class Timestamps {
/**
* Convert a Timestamp to the number of microseconds elapsed from the epoch.
*
- * <p>The result will be rounded down to the nearest microsecond. E.g., if the
- * timestamp represents "1969-12-31T23:59:59.999999999Z", it will be rounded
- * to -1 millisecond.
+ * <p>The result will be rounded down to the nearest microsecond. E.g., if the timestamp
+ * represents "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 millisecond.
*/
public static long toMicros(Timestamp timestamp) {
- return timestamp.getSeconds() * MICROS_PER_SECOND
- + timestamp.getNanos() / NANOS_PER_MICROSECOND;
+ checkValid(timestamp);
+ return checkedAdd(
+ checkedMultiply(timestamp.getSeconds(), MICROS_PER_SECOND),
+ timestamp.getNanos() / NANOS_PER_MICROSECOND);
}
- /**
- * Create a Timestamp from the number of nanoseconds elapsed from the epoch.
- */
+ /** Create a Timestamp from the number of nanoseconds elapsed from the epoch. */
public static Timestamp fromNanos(long nanoseconds) {
return normalizedTimestamp(
nanoseconds / NANOS_PER_SECOND, (int) (nanoseconds % NANOS_PER_SECOND));
}
- /**
- * Convert a Timestamp to the number of nanoseconds elapsed from the epoch.
- */
+ /** Convert a Timestamp to the number of nanoseconds elapsed from the epoch. */
public static long toNanos(Timestamp timestamp) {
- return timestamp.getSeconds() * NANOS_PER_SECOND + timestamp.getNanos();
+ checkValid(timestamp);
+ return checkedAdd(
+ checkedMultiply(timestamp.getSeconds(), NANOS_PER_SECOND), timestamp.getNanos());
}
- /**
- * Calculate the difference between two timestamps.
- */
+ /** Calculate the difference between two timestamps. */
public static Duration between(Timestamp from, Timestamp to) {
+ checkValid(from);
+ checkValid(to);
return Durations.normalizedDuration(
- to.getSeconds() - from.getSeconds(), to.getNanos() - from.getNanos());
+ checkedSubtract(to.getSeconds(), from.getSeconds()),
+ checkedSubtract(to.getNanos(), from.getNanos()));
}
- /**
- * Add a duration to a timestamp.
- */
+ /** Add a duration to a timestamp. */
public static Timestamp add(Timestamp start, Duration length) {
+ checkValid(start);
+ Durations.checkValid(length);
return normalizedTimestamp(
- start.getSeconds() + length.getSeconds(), start.getNanos() + length.getNanos());
+ checkedAdd(start.getSeconds(), length.getSeconds()),
+ checkedAdd(start.getNanos(), length.getNanos()));
}
- /**
- * Subtract a duration from a timestamp.
- */
+ /** Subtract a duration from a timestamp. */
public static Timestamp subtract(Timestamp start, Duration length) {
+ checkValid(start);
+ Durations.checkValid(length);
return normalizedTimestamp(
- start.getSeconds() - length.getSeconds(), start.getNanos() - length.getNanos());
+ checkedSubtract(start.getSeconds(), length.getSeconds()),
+ checkedSubtract(start.getNanos(), length.getNanos()));
}
- private static Timestamp normalizedTimestamp(long seconds, int nanos) {
+ static Timestamp normalizedTimestamp(long seconds, int nanos) {
if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
- seconds += nanos / NANOS_PER_SECOND;
+ seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
nanos %= NANOS_PER_SECOND;
}
if (nanos < 0) {
- nanos += NANOS_PER_SECOND;
- seconds -= 1;
+ nanos += NANOS_PER_SECOND; // no overflow since nanos is negative (and we're adding)
+ seconds = checkedSubtract(seconds, 1);
}
- checkValid(seconds, nanos);
- return Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
+ Timestamp timestamp = Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
+ return checkValid(timestamp);
}
private static long parseTimezoneOffset(String value) throws ParseException {
@@ -324,7 +378,7 @@ public final class Timestamps {
result = result * 10;
if (i < value.length()) {
if (value.charAt(i) < '0' || value.charAt(i) > '9') {
- throw new ParseException("Invalid nanosecnds.", 0);
+ throw new ParseException("Invalid nanoseconds.", 0);
}
result += value.charAt(i) - '0';
}
@@ -332,11 +386,8 @@ public final class Timestamps {
return result;
}
- /**
- * Format the nano part of a timestamp or a duration.
- */
+ /** Format the nano part of a timestamp or a duration. */
static String formatNanos(int nanos) {
- assert nanos >= 1 && nanos <= 999999999;
// Determine whether to use 3, 6, or 9 digits for the nano part.
if (nanos % NANOS_PER_MILLISECOND == 0) {
return String.format("%1$03d", nanos / NANOS_PER_MILLISECOND);
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 6fc784ef..32739d44 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
@@ -60,12 +60,10 @@ import com.google.protobuf.util.JsonTestProto.TestOneof;
import com.google.protobuf.util.JsonTestProto.TestStruct;
import com.google.protobuf.util.JsonTestProto.TestTimestamp;
import com.google.protobuf.util.JsonTestProto.TestWrappers;
-
-import junit.framework.TestCase;
-
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
+import junit.framework.TestCase;
public class JsonFormatTest extends TestCase {
private void setAllFields(TestAllTypes.Builder builder) {
@@ -819,6 +817,15 @@ public class JsonFormatTest extends TestCase {
printer.print(message));
assertRoundTripEquals(message, registry);
+ TestAny messageWithDefaultAnyValue =
+ TestAny.newBuilder().setAnyValue(Any.getDefaultInstance()).build();
+ assertEquals(
+ "{\n"
+ + " \"anyValue\": {}\n"
+ + "}",
+ printer.print(messageWithDefaultAnyValue));
+ assertRoundTripEquals(messageWithDefaultAnyValue, registry);
+
// Well-known types have a special formatting when embedded in Any.
//
// 1. Any in Any.
@@ -952,6 +959,8 @@ public class JsonFormatTest extends TestCase {
+ "}",
printer.print(anyMessage));
assertRoundTripEquals(anyMessage, registry);
+
+ // 7. Value (number type) in Any
Value.Builder valueBuilder = Value.newBuilder();
valueBuilder.setNumberValue(1);
anyMessage = Any.pack(valueBuilder.build());
@@ -962,6 +971,95 @@ public class JsonFormatTest extends TestCase {
+ "}",
printer.print(anyMessage));
assertRoundTripEquals(anyMessage, registry);
+
+ // 8. Value (null type) in Any
+ anyMessage = Any.pack(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build());
+ assertEquals(
+ "{\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n"
+ + " \"value\": null\n"
+ + "}",
+ printer.print(anyMessage));
+ assertRoundTripEquals(anyMessage, registry);
+ }
+
+ public void testAnyInMaps() throws Exception {
+ JsonFormat.TypeRegistry registry =
+ JsonFormat.TypeRegistry.newBuilder().add(TestAllTypes.getDescriptor()).build();
+ JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry);
+
+ TestAny.Builder testAny = TestAny.newBuilder();
+ testAny.putAnyMap("int32_wrapper", Any.pack(Int32Value.newBuilder().setValue(123).build()));
+ testAny.putAnyMap("int64_wrapper", Any.pack(Int64Value.newBuilder().setValue(456).build()));
+ testAny.putAnyMap("timestamp", Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")));
+ testAny.putAnyMap("duration", Any.pack(Durations.parse("12345.1s")));
+ testAny.putAnyMap("field_mask", Any.pack(FieldMaskUtil.fromString("foo.bar,baz")));
+ Value numberValue = Value.newBuilder().setNumberValue(1.125).build();
+ Struct.Builder struct = Struct.newBuilder();
+ struct.putFields("number", numberValue);
+ testAny.putAnyMap("struct", Any.pack(struct.build()));
+ Value nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();
+ testAny.putAnyMap(
+ "list_value",
+ Any.pack(ListValue.newBuilder().addValues(numberValue).addValues(nullValue).build()));
+ testAny.putAnyMap("number_value", Any.pack(numberValue));
+ testAny.putAnyMap("any_value_number", Any.pack(Any.pack(numberValue)));
+ testAny.putAnyMap("any_value_default", Any.pack(Any.getDefaultInstance()));
+ testAny.putAnyMap("default", Any.getDefaultInstance());
+
+ assertEquals(
+ "{\n"
+ + " \"anyMap\": {\n"
+ + " \"int32_wrapper\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Int32Value\",\n"
+ + " \"value\": 123\n"
+ + " },\n"
+ + " \"int64_wrapper\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Int64Value\",\n"
+ + " \"value\": \"456\"\n"
+ + " },\n"
+ + " \"timestamp\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\",\n"
+ + " \"value\": \"1969-12-31T23:59:59Z\"\n"
+ + " },\n"
+ + " \"duration\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n"
+ + " \"value\": \"12345.100s\"\n"
+ + " },\n"
+ + " \"field_mask\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.FieldMask\",\n"
+ + " \"value\": \"foo.bar,baz\"\n"
+ + " },\n"
+ + " \"struct\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Struct\",\n"
+ + " \"value\": {\n"
+ + " \"number\": 1.125\n"
+ + " }\n"
+ + " },\n"
+ + " \"list_value\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.ListValue\",\n"
+ + " \"value\": [1.125, null]\n"
+ + " },\n"
+ + " \"number_value\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n"
+ + " \"value\": 1.125\n"
+ + " },\n"
+ + " \"any_value_number\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n"
+ + " \"value\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n"
+ + " \"value\": 1.125\n"
+ + " }\n"
+ + " },\n"
+ + " \"any_value_default\": {\n"
+ + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n"
+ + " \"value\": {}\n"
+ + " },\n"
+ + " \"default\": {}\n"
+ + " }\n"
+ + "}",
+ printer.print(testAny.build()));
+ assertRoundTripEquals(testAny.build(), registry);
}
public void testParserMissingTypeUrl() throws Exception {
@@ -1016,8 +1114,10 @@ public class JsonFormatTest extends TestCase {
public void testParserRejectInvalidBase64() throws Exception {
assertRejects("optionalBytes", "!@#$");
- // We use standard BASE64 with paddings.
- assertRejects("optionalBytes", "AQI");
+ }
+
+ public void testParserAcceptBase64Variants() throws Exception {
+ assertAccepts("optionalBytes", "AQI");
}
public void testParserRejectInvalidEnumValue() throws Exception {
@@ -1030,6 +1130,22 @@ public class JsonFormatTest extends TestCase {
}
}
+ public void testParserUnknownFields() throws Exception {
+ try {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ String json = "{\n" + " \"unknownField\": \"XXX\"\n" + "}";
+ JsonFormat.parser().merge(json, builder);
+ fail("Exception is expected.");
+ } catch (InvalidProtocolBufferException e) {
+ // Expected.
+ }
+ }
+ public void testParserIgnoringUnknownFields() throws Exception {
+ TestAllTypes.Builder builder = TestAllTypes.newBuilder();
+ String json = "{\n" + " \"unknownField\": \"XXX\"\n" + "}";
+ JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
+ }
+
public void testCustomJsonName() throws Exception {
TestCustomJsonName message = TestCustomJsonName.newBuilder().setValue(12345).build();
assertEquals("{\n" + " \"@value\": 12345\n" + "}", JsonFormat.printer().print(message));
diff --git a/java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java b/java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java
index a41528ec..5af83d88 100644
--- a/java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java
+++ b/java/util/src/test/java/com/google/protobuf/util/TimeUtilTest.java
@@ -32,14 +32,11 @@ package com.google.protobuf.util;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
-
-import junit.framework.TestCase;
-
-import org.junit.Assert;
-
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
+import junit.framework.TestCase;
+import org.junit.Assert;
/** Unit tests for {@link TimeUtil}. */
public class TimeUtilTest extends TestCase {
diff --git a/java/util/src/test/proto/com/google/protobuf/util/json_test.proto b/java/util/src/test/proto/com/google/protobuf/util/json_test.proto
index 4bf223f2..bd22f65a 100644
--- a/java/util/src/test/proto/com/google/protobuf/util/json_test.proto
+++ b/java/util/src/test/proto/com/google/protobuf/util/json_test.proto
@@ -195,6 +195,7 @@ message TestStruct {
message TestAny {
google.protobuf.Any any_value = 1;
+ map<string, google.protobuf.Any> any_map = 2;
}
message TestCustomJsonName {
diff --git a/javanano/pom.xml b/javanano/pom.xml
index e6a03d15..6bac76c9 100644
--- a/javanano/pom.xml
+++ b/javanano/pom.xml
@@ -10,7 +10,7 @@
</parent>
<groupId>com.google.protobuf.nano</groupId>
<artifactId>protobuf-javanano</artifactId>
- <version>3.0.0-alpha-7</version>
+ <version>3.1.0</version>
<packaging>bundle</packaging>
<name>Protocol Buffer JavaNano API</name>
<description>
@@ -164,8 +164,8 @@
<configuration>
<instructions>
<Bundle-DocURL>https://developers.google.com/protocol-buffers/</Bundle-DocURL>
- <Bundle-SymbolicName>com.google.protobuf</Bundle-SymbolicName>
- <Export-Package>com.google.protobuf;version=3.0.0-alpha-7</Export-Package>
+ <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>
diff --git a/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java b/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java
index 3864d38a..9a83d6d3 100644
--- a/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java
+++ b/javanano/src/main/java/com/google/protobuf/nano/InvalidProtocolBufferNanoException.java
@@ -48,7 +48,7 @@ public class InvalidProtocolBufferNanoException extends IOException {
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 than the " +
+ "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.");
}
diff --git a/jenkins/build_and_run_docker.sh b/jenkins/build_and_run_docker.sh
index abc6f055..50e1e8c6 100755
--- a/jenkins/build_and_run_docker.sh
+++ b/jenkins/build_and_run_docker.sh
@@ -33,6 +33,7 @@ docker run \
"$@" \
-e CCACHE_DIR=$CCACHE_DIR \
-e EXTERNAL_GIT_ROOT="/var/local/jenkins/protobuf" \
+ -e TEST_SET="$TEST_SET" \
-e THIS_IS_REALLY_NEEDED='see https://github.com/docker/docker/issues/14203 for why docker is awful' \
-v "$git_root:/var/local/jenkins/protobuf:ro" \
-v $CCACHE_DIR:$CCACHE_DIR \
diff --git a/jenkins/buildcmds/pull_request.sh b/jenkins/buildcmds/pull_request.sh
index 01fda798..51e4bfa4 100755
--- a/jenkins/buildcmds/pull_request.sh
+++ b/jenkins/buildcmds/pull_request.sh
@@ -12,4 +12,5 @@
export DOCKERFILE_DIR=jenkins/docker
export DOCKER_RUN_SCRIPT=jenkins/pull_request_in_docker.sh
export OUTPUT_DIR=testoutput
+export TEST_SET="csharp java_jdk7 javanano_jdk7 java_oracle7 javanano_oracle7 python python_cpp ruby_all javascript golang php_all"
./jenkins/build_and_run_docker.sh
diff --git a/jenkins/buildcmds/pull_request_32.sh b/jenkins/buildcmds/pull_request_32.sh
new file mode 100755
index 00000000..bf0fb7ff
--- /dev/null
+++ b/jenkins/buildcmds/pull_request_32.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+#
+# This is the top-level script we give to Jenkins as the entry point for
+# running the "pull request 32" project:
+#
+# https://grpc-testing.appspot.com/view/Protocol%20Buffers/job/Protocol%20Buffers%20Pull%20Request%2032/
+#
+# This script selects a specific Dockerfile (for building a Docker image) and
+# a script to run inside that image. Then we delegate to the general
+# build_and_run_docker.sh script.
+
+export DOCKERFILE_DIR=jenkins/docker32
+export DOCKER_RUN_SCRIPT=jenkins/pull_request_in_docker.sh
+export OUTPUT_DIR=testoutput
+export TEST_SET="php_all_32"
+./jenkins/build_and_run_docker.sh
diff --git a/jenkins/docker/Dockerfile b/jenkins/docker/Dockerfile
index 53ac38f3..919a2b61 100644
--- a/jenkins/docker/Dockerfile
+++ b/jenkins/docker/Dockerfile
@@ -14,25 +14,29 @@ RUN echo 'deb http://ppa.launchpad.net/fkrull/deadsnakes/ubuntu trusty main' > /
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys DB82666C
# Apt source for Oracle Java.
-run echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' > /etc/apt/sources.list.d/webupd8team-java-trusty.list && \
+RUN echo 'deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main' > /etc/apt/sources.list.d/webupd8team-java-trusty.list && \
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 && \
echo "oracle-java7-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections
# Apt source for Mono
-run echo "deb http://download.mono-project.com/repo/debian wheezy main" | tee /etc/apt/sources.list.d/mono-xamarin.list && \
+RUN echo "deb http://download.mono-project.com/repo/debian wheezy main" | tee /etc/apt/sources.list.d/mono-xamarin.list && \
echo "deb http://download.mono-project.com/repo/debian wheezy-libjpeg62-compat main" | tee -a /etc/apt/sources.list.d/mono-xamarin.list && \
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
+# Apt source for php
+RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main" | tee /etc/apt/sources.list.d/various-php.list && \
+ apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F4FCBB07
+
# Install dotnet SDK based on https://www.microsoft.com/net/core#debian
# (Ubuntu instructions need apt to support https)
-RUN apt-get update && apt-get install -y curl libunwind8 gettext && \
- curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=809130 && \
+RUN apt-get update && apt-get install -y --force-yes curl libunwind8 gettext && \
+ curl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=809130 && \
mkdir -p /opt/dotnet && tar zxf dotnet.tar.gz -C /opt/dotnet && \
ln -s /opt/dotnet/dotnet /usr/local/bin
# Install dependencies. We start with the basic ones require to build protoc
# and the C++ build
-RUN apt-get update && apt-get install -y \
+RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
autoconf \
autotools-dev \
build-essential \
@@ -71,6 +75,21 @@ RUN apt-get update && apt-get install -y \
python3.4-dev \
# -- For Ruby --
ruby \
+ # -- For C++ benchmarks --
+ cmake \
+ # -- For PHP --
+ php5.5 \
+ php5.5-dev \
+ php5.5-xml \
+ php5.6 \
+ php5.6-dev \
+ php5.6-xml \
+ php7.0 \
+ php7.0-dev \
+ php7.0-xml \
+ phpunit \
+ valgrind \
+ libxml2-dev \
&& apt-get clean
##################
@@ -113,15 +132,45 @@ ENV MVN mvn --batch-mode
RUN cd /tmp && \
git clone https://github.com/google/protobuf.git && \
cd protobuf && \
+ git reset 734930f9197b7bc97c3c794c7a949fee2a08c280 && \
./autogen.sh && \
./configure && \
- make -j6 && \
+ make -j4 && \
cd java && \
$MVN install dependency:go-offline -Dmaven.repo.local=$MAVEN_REPO && \
cd ../javanano && \
$MVN install dependency:go-offline -Dmaven.repo.local=$MAVEN_REPO
##################
+# PHP dependencies.
+RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
+RUN php composer-setup.php
+RUN mv composer.phar /usr/bin/composer
+RUN php -r "unlink('composer-setup.php');"
+RUN cd /tmp && \
+ cd protobuf && \
+ ln -sfn /usr/bin/php5.5 /usr/bin/php && \
+ ln -sfn /usr/bin/php-config5.5 /usr/bin/php-config && \
+ ln -sfn /usr/bin/phpize5.5 /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-5.5 && \
+ ln -sfn /usr/bin/php5.6 /usr/bin/php && \
+ ln -sfn /usr/bin/php-config5.6 /usr/bin/php-config && \
+ ln -sfn /usr/bin/phpize5.6 /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-5.6 && \
+ ln -sfn /usr/bin/php7.0 /usr/bin/php && \
+ ln -sfn /usr/bin/php-config7.0 /usr/bin/php-config && \
+ ln -sfn /usr/bin/phpize7.0 /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-7.0
+RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
+RUN mv mirror php-5.5.38.tar.bz2
+RUN tar -xvf php-5.5.38.tar.bz2
+RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
+ make && make install
+
+##################
# Go dependencies.
RUN apt-get install -y \
# -- For go -- \
@@ -129,7 +178,7 @@ RUN apt-get install -y \
##################
# Javascript dependencies.
-Run apt-get install -y \
+RUN apt-get install -y \
# -- For javascript -- \
npm
diff --git a/jenkins/docker32/Dockerfile b/jenkins/docker32/Dockerfile
new file mode 100644
index 00000000..a36338b4
--- /dev/null
+++ b/jenkins/docker32/Dockerfile
@@ -0,0 +1,111 @@
+# This Dockerfile specifies the recipe for creating an image for the tests
+# to run in.
+#
+# We install as many test dependencies here as we can, because these setup
+# steps can be cached. They do *not* run every time we run the build.
+# The Docker image is only rebuilt when the Dockerfile (ie. this file)
+# changes.
+
+# Base Dockerfile for gRPC dev images
+FROM 32bit/debian:latest
+
+# Apt source for php
+RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu trusty main" | tee /etc/apt/sources.list.d/various-php.list && \
+ apt-key adv --keyserver keyserver.ubuntu.com --recv-keys F4FCBB07
+
+# Install dependencies. We start with the basic ones require to build protoc
+# and the C++ build
+RUN apt-get clean && apt-get update && apt-get install -y --force-yes \
+ autoconf \
+ autotools-dev \
+ build-essential \
+ bzip2 \
+ ccache \
+ curl \
+ gcc \
+ git \
+ libc6 \
+ libc6-dbg \
+ libc6-dev \
+ libgtest-dev \
+ libtool \
+ make \
+ parallel \
+ time \
+ wget \
+ unzip \
+ # -- For python --
+ python-setuptools \
+ python-pip \
+ python-dev \
+ # -- For C++ benchmarks --
+ cmake \
+ # -- For PHP --
+ php5.5 \
+ php5.5-dev \
+ php5.5-xml \
+ php5.6 \
+ php5.6-dev \
+ php5.6-xml \
+ php7.0 \
+ php7.0-dev \
+ php7.0-xml \
+ phpunit \
+ valgrind \
+ libxml2-dev \
+ && apt-get clean
+
+##################
+# PHP dependencies.
+RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
+RUN php composer-setup.php
+RUN mv composer.phar /usr/bin/composer
+RUN php -r "unlink('composer-setup.php');"
+RUN cd /tmp && \
+ git clone https://github.com/google/protobuf.git && \
+ cd protobuf && \
+ git reset 734930f9197b7bc97c3c794c7a949fee2a08c280 && \
+ ln -sfn /usr/bin/php5.5 /usr/bin/php && \
+ ln -sfn /usr/bin/php-config5.5 /usr/bin/php-config && \
+ ln -sfn /usr/bin/phpize5.5 /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-5.5 && \
+ ln -sfn /usr/bin/php5.6 /usr/bin/php && \
+ ln -sfn /usr/bin/php-config5.6 /usr/bin/php-config && \
+ ln -sfn /usr/bin/phpize5.6 /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-5.6 && \
+ ln -sfn /usr/bin/php7.0 /usr/bin/php && \
+ ln -sfn /usr/bin/php-config7.0 /usr/bin/php-config && \
+ ln -sfn /usr/bin/phpize7.0 /usr/bin/phpize && \
+ composer install && \
+ mv vendor /usr/local/vendor-7.0
+RUN wget http://am1.php.net/get/php-5.5.38.tar.bz2/from/this/mirror
+RUN mv mirror php-5.5.38.tar.bz2
+RUN tar -xvf php-5.5.38.tar.bz2
+RUN cd php-5.5.38 && ./configure --enable-maintainer-zts --prefix=/usr/local/php-5.5-zts && \
+ make && make install && make clean && cd ..
+RUN cd php-5.5.38 && ./configure --enable-bcmath --prefix=/usr/local/php-5.5-bc && \
+ make && make install && make clean && cd ..
+
+##################
+# Python dependencies
+
+# These packages exist in apt-get, but their versions are too old, so we have
+# to get updates from pip.
+
+RUN pip install pip --upgrade
+RUN pip install virtualenv tox yattag
+
+##################
+# Prepare ccache
+
+RUN ln -s /usr/bin/ccache /usr/local/bin/gcc
+RUN ln -s /usr/bin/ccache /usr/local/bin/g++
+RUN ln -s /usr/bin/ccache /usr/local/bin/cc
+RUN ln -s /usr/bin/ccache /usr/local/bin/c++
+RUN ln -s /usr/bin/ccache /usr/local/bin/clang
+RUN ln -s /usr/bin/ccache /usr/local/bin/clang++
+
+# Define the default command.
+CMD ["bash"]
diff --git a/jenkins/pull_request_in_docker.sh b/jenkins/pull_request_in_docker.sh
index 78a9253a..10daf0a5 100755
--- a/jenkins/pull_request_in_docker.sh
+++ b/jenkins/pull_request_in_docker.sh
@@ -45,19 +45,11 @@ TIME_CMD="/usr/bin/time -f %e -o $LOG_OUTPUT_DIR/1/cpp/build_time"
$TIME_CMD $TEST_SCRIPT cpp > >(tee $CPP_STDOUT) 2> >(tee $CPP_STDERR >&2)
-# Other tests are run in parallel.
+# Other tests are run in parallel. TEST_SET is defined in
+# buildcmds/pull_request{_32}.sh
parallel --results $LOG_OUTPUT_DIR --joblog $OUTPUT_DIR/joblog $TEST_SCRIPT ::: \
- csharp \
- java_jdk7 \
- javanano_jdk7 \
- java_oracle7 \
- javanano_oracle7 \
- python \
- python_cpp \
- ruby_all \
- javascript \
- golang \
+ $TEST_SET \
|| true # Process test results even if tests fail.
cat $OUTPUT_DIR/joblog
diff --git a/js/binary/proto_test.js b/js/binary/proto_test.js
index 14d0f42e..26e1d30f 100644
--- a/js/binary/proto_test.js
+++ b/js/binary/proto_test.js
@@ -496,7 +496,7 @@ describe('protoBinaryTest', function() {
msg.setRepeatedBytesList([BYTES_B64, BYTES_B64]);
assertGetters();
- msg.setRepeatedBytesList(null);
+ msg.setRepeatedBytesList([]);
assertEquals(0, msg.getRepeatedBytesList().length);
assertEquals(0, msg.getRepeatedBytesList_asB64().length);
assertEquals(0, msg.getRepeatedBytesList_asU8().length);
diff --git a/js/commonjs/export.js b/js/commonjs/export.js
index fb56b30b..2403b1a4 100644
--- a/js/commonjs/export.js
+++ b/js/commonjs/export.js
@@ -11,7 +11,9 @@ goog.require('jspb.BinaryWriter');
goog.require('jspb.ExtensionFieldBinaryInfo');
goog.require('jspb.ExtensionFieldInfo');
goog.require('jspb.Message');
+goog.require('jspb.Map');
+exports.Map = jspb.Map;
exports.Message = jspb.Message;
exports.BinaryReader = jspb.BinaryReader;
exports.BinaryWriter = jspb.BinaryWriter;
diff --git a/js/debug.js b/js/debug.js
index 3c1ada02..46b24853 100644
--- a/js/debug.js
+++ b/js/debug.js
@@ -95,8 +95,7 @@ jspb.debug.dump_ = function(thing) {
if (match && name != 'getExtension' &&
name != 'getJsPbMessageId') {
var has = 'has' + match[1];
- if (!thing[has] || thing[has]())
- {
+ if (!thing[has] || thing[has]()) {
var val = thing[name]();
object[jspb.debug.formatFieldName_(match[1])] = jspb.debug.dump_(val);
}
diff --git a/js/debug_test.js b/js/debug_test.js
index 01cbf891..702cc76e 100644
--- a/js/debug_test.js
+++ b/js/debug_test.js
@@ -65,7 +65,7 @@ describe('debugTest', function() {
'aBoolean': true
}, jspb.debug.dump(message));
- message.setAString(undefined);
+ message.clearAString();
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
diff --git a/js/map.js b/js/map.js
index e6406a60..0f8401c4 100644
--- a/js/map.js
+++ b/js/map.js
@@ -103,7 +103,10 @@ jspb.Map.prototype.toArray = function() {
var m = this.map_;
for (var p in m) {
if (Object.prototype.hasOwnProperty.call(m, p)) {
- m[p].valueWrapper.toArray();
+ var valueWrapper = /** @type {?jspb.Message} */ (m[p].valueWrapper);
+ if (valueWrapper) {
+ valueWrapper.toArray();
+ }
}
}
}
@@ -343,13 +346,13 @@ jspb.Map.prototype.has = function(key) {
* number.
* @param {number} fieldNumber
* @param {!jspb.BinaryWriter} writer
- * @param {function(this:jspb.BinaryWriter,number,K)=} keyWriterFn
+ * @param {!function(this:jspb.BinaryWriter,number,K)} keyWriterFn
* The method on BinaryWriter that writes type K to the stream.
- * @param {function(this:jspb.BinaryWriter,number,V)|
- * function(this:jspb.BinaryReader,V,?)=} valueWriterFn
+ * @param {!function(this:jspb.BinaryWriter,number,V)|
+ * function(this:jspb.BinaryReader,V,?)} valueWriterFn
* The method on BinaryWriter that writes type V to the stream. May be
* writeMessage, in which case the second callback arg form is used.
- * @param {?function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback
+ * @param {function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback
* The BinaryWriter serialization callback for type V, if V is a message
* type.
*/
@@ -376,14 +379,15 @@ jspb.Map.prototype.serializeBinary = function(
* Read one key/value message from the given BinaryReader. Compatible as the
* `reader` callback parameter to jspb.BinaryReader.readMessage, to be called
* when a key/value pair submessage is encountered.
+ * @template K, V
* @param {!jspb.Map} map
* @param {!jspb.BinaryReader} reader
- * @param {function(this:jspb.BinaryReader):K=} keyReaderFn
+ * @param {!function(this:jspb.BinaryReader):K} keyReaderFn
* The method on BinaryReader that reads type K from the stream.
*
- * @param {function(this:jspb.BinaryReader):V|
- * function(this:jspb.BinaryReader,V,
- * function(V,!jspb.BinaryReader))=} valueReaderFn
+ * @param {!function(this:jspb.BinaryReader):V|
+ * function(this:jspb.BinaryReader,V,
+ * function(V,!jspb.BinaryReader))} valueReaderFn
* The method on BinaryReader that reads type V from the stream. May be
* readMessage, in which case the second callback arg form is used.
*
diff --git a/js/maps_test.js b/js/maps_test.js
new file mode 100755
index 00000000..0d442f4f
--- /dev/null
+++ b/js/maps_test.js
@@ -0,0 +1,301 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+goog.require('goog.testing.asserts');
+goog.require('goog.userAgent');
+
+// CommonJS-LoadFromFile: testbinary_pb proto.jspb.test
+goog.require('proto.jspb.test.MapValueEnum');
+goog.require('proto.jspb.test.MapValueMessage');
+goog.require('proto.jspb.test.TestMapFields');
+
+// CommonJS-LoadFromFile: test_pb proto.jspb.test
+goog.require('proto.jspb.test.MapValueMessageNoBinary');
+goog.require('proto.jspb.test.TestMapFieldsNoBinary');
+
+/**
+ * Helper: check that the given map has exactly this set of (sorted) entries.
+ * @param {!jspb.Map} map
+ * @param {!Array<!Array<?>>} entries
+ */
+function checkMapEquals(map, entries) {
+ var arr = map.toArray();
+ assertEquals(arr.length, entries.length);
+ for (var i = 0; i < arr.length; i++) {
+ assertElementsEquals(arr[i], entries[i]);
+ }
+}
+
+/**
+ * Converts an ES6 iterator to an array.
+ * @template T
+ * @param {!Iterator<T>} iter an iterator
+ * @return {!Array<T>}
+ */
+function toArray(iter) {
+ var arr = [];
+ while (true) {
+ var val = iter.next();
+ if (val.done) {
+ break;
+ }
+ arr.push(val.value);
+ }
+ return arr;
+}
+
+
+/**
+ * Helper: generate test methods for this TestMapFields class.
+ * @param {?} msgInfo
+ * @param {?} submessageCtor
+ * @param {!string} suffix
+ */
+function makeTests(msgInfo, submessageCtor, suffix) {
+ /**
+ * Helper: fill all maps on a TestMapFields.
+ * @param {?} msg
+ */
+ var fillMapFields = function(msg) {
+ msg.getMapStringStringMap().set('asdf', 'jkl;').set('key 2', 'hello world');
+ msg.getMapStringInt32Map().set('a', 1).set('b', -2);
+ msg.getMapStringInt64Map().set('c', 0x100000000).set('d', 0x200000000);
+ msg.getMapStringBoolMap().set('e', true).set('f', false);
+ msg.getMapStringDoubleMap().set('g', 3.14159).set('h', 2.71828);
+ msg.getMapStringEnumMap()
+ .set('i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR)
+ .set('j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ);
+ msg.getMapStringMsgMap()
+ .set('k', new submessageCtor())
+ .set('l', new submessageCtor());
+ msg.getMapStringMsgMap().get('k').setFoo(42);
+ msg.getMapStringMsgMap().get('l').setFoo(84);
+ msg.getMapInt32StringMap().set(-1, 'a').set(42, 'b');
+ msg.getMapInt64StringMap().set(0x123456789abc, 'c').set(0xcba987654321, 'd');
+ msg.getMapBoolStringMap().set(false, 'e').set(true, 'f');
+ };
+
+ /**
+ * Helper: check all maps on a TestMapFields.
+ * @param {?} msg
+ */
+ var checkMapFields = function(msg) {
+ checkMapEquals(msg.getMapStringStringMap(), [
+ ['asdf', 'jkl;'],
+ ['key 2', 'hello world']
+ ]);
+ checkMapEquals(msg.getMapStringInt32Map(), [
+ ['a', 1],
+ ['b', -2]
+ ]);
+ checkMapEquals(msg.getMapStringInt64Map(), [
+ ['c', 0x100000000],
+ ['d', 0x200000000]
+ ]);
+ checkMapEquals(msg.getMapStringBoolMap(), [
+ ['e', true],
+ ['f', false]
+ ]);
+ checkMapEquals(msg.getMapStringDoubleMap(), [
+ ['g', 3.14159],
+ ['h', 2.71828]
+ ]);
+ checkMapEquals(msg.getMapStringEnumMap(), [
+ ['i', proto.jspb.test.MapValueEnum.MAP_VALUE_BAR],
+ ['j', proto.jspb.test.MapValueEnum.MAP_VALUE_BAZ]
+ ]);
+ checkMapEquals(msg.getMapInt32StringMap(), [
+ [-1, 'a'],
+ [42, 'b']
+ ]);
+ checkMapEquals(msg.getMapInt64StringMap(), [
+ [0x123456789abc, 'c'],
+ [0xcba987654321, 'd']
+ ]);
+ checkMapEquals(msg.getMapBoolStringMap(), [
+ [false, 'e'],
+ [true, 'f']
+ ]);
+
+ assertEquals(msg.getMapStringMsgMap().getLength(), 2);
+ assertEquals(msg.getMapStringMsgMap().get('k').getFoo(), 42);
+ assertEquals(msg.getMapStringMsgMap().get('l').getFoo(), 84);
+
+ var entries = toArray(msg.getMapStringMsgMap().entries());
+ assertEquals(entries.length, 2);
+ entries.forEach(function(entry) {
+ var key = entry[0];
+ var val = entry[1];
+ assert(val === msg.getMapStringMsgMap().get(key));
+ });
+
+ msg.getMapStringMsgMap().forEach(function(val, key) {
+ assert(val === msg.getMapStringMsgMap().get(key));
+ });
+ };
+
+ it('testMapStringStringField' + suffix, function() {
+ var msg = new msgInfo.constructor();
+ assertEquals(msg.getMapStringStringMap().getLength(), 0);
+ assertEquals(msg.getMapStringInt32Map().getLength(), 0);
+ assertEquals(msg.getMapStringInt64Map().getLength(), 0);
+ assertEquals(msg.getMapStringBoolMap().getLength(), 0);
+ assertEquals(msg.getMapStringDoubleMap().getLength(), 0);
+ assertEquals(msg.getMapStringEnumMap().getLength(), 0);
+ assertEquals(msg.getMapStringMsgMap().getLength(), 0);
+
+ // Re-create to clear out any internally-cached wrappers, etc.
+ msg = new msgInfo.constructor();
+ var m = msg.getMapStringStringMap();
+ assertEquals(m.has('asdf'), false);
+ assertEquals(m.get('asdf'), undefined);
+ m.set('asdf', 'hello world');
+ assertEquals(m.has('asdf'), true);
+ assertEquals(m.get('asdf'), 'hello world');
+ m.set('jkl;', 'key 2');
+ assertEquals(m.has('jkl;'), true);
+ assertEquals(m.get('jkl;'), 'key 2');
+ assertEquals(m.getLength(), 2);
+ var it = m.entries();
+ assertElementsEquals(it.next().value, ['asdf', 'hello world']);
+ assertElementsEquals(it.next().value, ['jkl;', 'key 2']);
+ assertEquals(it.next().done, true);
+ checkMapEquals(m, [
+ ['asdf', 'hello world'],
+ ['jkl;', 'key 2']
+ ]);
+ m.del('jkl;');
+ assertEquals(m.has('jkl;'), false);
+ assertEquals(m.get('jkl;'), undefined);
+ assertEquals(m.getLength(), 1);
+ it = m.keys();
+ assertEquals(it.next().value, 'asdf');
+ assertEquals(it.next().done, true);
+ it = m.values();
+ assertEquals(it.next().value, 'hello world');
+ assertEquals(it.next().done, true);
+
+ var count = 0;
+ m.forEach(function(value, key, map) {
+ assertEquals(map, m);
+ assertEquals(key, 'asdf');
+ assertEquals(value, 'hello world');
+ count++;
+ });
+ assertEquals(count, 1);
+
+ m.clear();
+ assertEquals(m.getLength(), 0);
+ });
+
+
+ /**
+ * Tests operations on maps with all key and value types.
+ */
+ it('testAllMapTypes' + suffix, function() {
+ var msg = new msgInfo.constructor();
+ fillMapFields(msg);
+ checkMapFields(msg);
+ });
+
+
+ if (msgInfo.deserializeBinary) {
+ /**
+ * Tests serialization and deserialization in binary format.
+ */
+ it('testBinaryFormat' + suffix, function() {
+ if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(10)) {
+ // IE8/9 currently doesn't support binary format because they lack
+ // TypedArray.
+ return;
+ }
+
+ // Check that the format is correct.
+ var msg = new msgInfo.constructor();
+ msg.getMapStringStringMap().set('A', 'a');
+ var serialized = msg.serializeBinary();
+ var expectedSerialized = [
+ 0x0a, 0x6, // field 1 (map_string_string), delimited, length 6
+ 0x0a, 0x1, // field 1 in submessage (key), delimited, length 1
+ 0x41, // ASCII 'A'
+ 0x12, 0x1, // field 2 in submessage (value), delimited, length 1
+ 0x61 // ASCII 'a'
+ ];
+ assertEquals(serialized.length, expectedSerialized.length);
+ for (var i = 0; i < serialized.length; i++) {
+ assertEquals(serialized[i], expectedSerialized[i]);
+ }
+
+ // Check that all map fields successfully round-trip.
+ msg = new msgInfo.constructor();
+ fillMapFields(msg);
+ serialized = msg.serializeBinary();
+ var decoded = msgInfo.deserializeBinary(serialized);
+ checkMapFields(decoded);
+ });
+ }
+
+ /**
+ * Exercises the lazy map<->underlying array sync.
+ */
+ it('testLazyMapSync' + suffix, function() {
+ // Start with a JSPB array containing a few map entries.
+ var entries = [
+ ['a', 'entry 1'],
+ ['c', 'entry 2'],
+ ['b', 'entry 3']
+ ];
+ var msg = new msgInfo.constructor([entries]);
+ assertEquals(entries.length, 3);
+ assertEquals(entries[0][0], 'a');
+ assertEquals(entries[1][0], 'c');
+ assertEquals(entries[2][0], 'b');
+ msg.getMapStringStringMap().del('a');
+ assertEquals(entries.length, 3); // not yet sync'd
+ msg.toArray(); // force a sync
+ assertEquals(entries.length, 2);
+ assertEquals(entries[0][0], 'b'); // now in sorted order
+ assertEquals(entries[1][0], 'c');
+
+ var a = msg.toArray();
+ assertEquals(a[0], entries); // retains original reference
+ });
+}
+
+describe('mapsTest', function() {
+ makeTests({
+ constructor: proto.jspb.test.TestMapFields,
+ deserializeBinary: proto.jspb.test.TestMapFields.deserializeBinary
+ }, proto.jspb.test.MapValueMessage, "_Binary");
+ makeTests({
+ constructor: proto.jspb.test.TestMapFieldsNoBinary,
+ deserializeBinary: null
+ }, proto.jspb.test.MapValueMessageNoBinary, "_NoBinary");
+});
diff --git a/js/message.js b/js/message.js
index 631ebe69..8def763e 100644
--- a/js/message.js
+++ b/js/message.js
@@ -106,17 +106,17 @@ jspb.ExtensionFieldInfo = function(fieldNumber, fieldName, ctor, toObjectFn,
/**
* Stores binary-related information for a single extension field.
* @param {!jspb.ExtensionFieldInfo<T>} fieldInfo
- * @param {?function(number,?)=} binaryReaderFn
- * @param {?function(number,?)|function(number,?,?,?,?,?)=} binaryWriterFn
- * @param {?function(?,?)=} opt_binaryMessageSerializeFn
- * @param {?function(?,?)=} opt_binaryMessageDeserializeFn
- * @param {?boolean=} opt_isPacked
+ * @param {!function(number,?)} binaryReaderFn
+ * @param {!function(number,?)|function(number,?,?,?,?,?)} binaryWriterFn
+ * @param {function(?,?)=} opt_binaryMessageSerializeFn
+ * @param {function(?,?)=} opt_binaryMessageDeserializeFn
+ * @param {boolean=} opt_isPacked
* @constructor
* @struct
* @template T
*/
jspb.ExtensionFieldBinaryInfo = function(fieldInfo, binaryReaderFn, binaryWriterFn,
- binaryMessageSerializeFn, binaryMessageDeserializeFn, isPacked) {
+ opt_binaryMessageSerializeFn, opt_binaryMessageDeserializeFn, opt_isPacked) {
/** @const */
this.fieldInfo = fieldInfo;
/** @const */
@@ -124,11 +124,11 @@ jspb.ExtensionFieldBinaryInfo = function(fieldInfo, binaryReaderFn, binaryWriter
/** @const */
this.binaryWriterFn = binaryWriterFn;
/** @const */
- this.binaryMessageSerializeFn = binaryMessageSerializeFn;
+ this.binaryMessageSerializeFn = opt_binaryMessageSerializeFn;
/** @const */
- this.binaryMessageDeserializeFn = binaryMessageDeserializeFn;
+ this.binaryMessageDeserializeFn = opt_binaryMessageDeserializeFn;
/** @const */
- this.isPacked = isPacked;
+ this.isPacked = opt_isPacked;
};
/**
@@ -744,7 +744,7 @@ jspb.Message.assertConsistentTypes_ = function(array) {
* @return {T} The field's value.
* @protected
*/
-jspb.Message.getFieldProto3 = function(msg, fieldNumber, defaultValue) {
+jspb.Message.getFieldWithDefault = function(msg, fieldNumber, defaultValue) {
var value = jspb.Message.getField(msg, fieldNumber);
if (value == null) {
return defaultValue;
@@ -755,6 +755,18 @@ jspb.Message.getFieldProto3 = function(msg, fieldNumber, defaultValue) {
/**
+ * Alias for getFieldWithDefault used by older generated code.
+ * @template T
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {T} defaultValue The default value.
+ * @return {T} The field's value.
+ * @protected
+ */
+jspb.Message.getFieldProto3 = jspb.Message.getFieldWithDefault;
+
+
+/**
* Gets the value of a map field, lazily creating the map container if
* necessary.
*
@@ -811,6 +823,24 @@ jspb.Message.setField = function(msg, fieldNumber, value) {
/**
+ * Adds a value to a repeated, primitive field.
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {string|number|boolean|!Uint8Array} value New value
+ * @param {number=} opt_index Index where to put new value.
+ * @protected
+ */
+jspb.Message.addToRepeatedField = function(msg, fieldNumber, value, opt_index) {
+ var arr = jspb.Message.getField(msg, fieldNumber);
+ if (opt_index != undefined) {
+ arr.splice(opt_index, 0, value);
+ } else {
+ arr.push(value);
+ }
+};
+
+
+/**
* Sets the value of a field in a oneof union and clears all other fields in
* the union.
* @param {!jspb.Message} msg A jspb proto.
@@ -907,6 +937,24 @@ jspb.Message.getWrapperField = function(msg, ctor, fieldNumber, opt_required) {
* @protected
*/
jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
+ jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
+ var val = msg.wrappers_[fieldNumber];
+ if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
+ val = msg.wrappers_[fieldNumber] = [];
+ }
+ return /** @type {!Array<!jspb.Message>} */ (val);
+};
+
+
+/**
+ * Wraps underlying array into proto message representation if it wasn't done
+ * before.
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {function(new:jspb.Message, ?Array)} ctor Constructor for the field.
+ * @param {number} fieldNumber The field number.
+ * @private
+ */
+jspb.Message.wrapRepeatedField_ = function(msg, ctor, fieldNumber) {
if (!msg.wrappers_) {
msg.wrappers_ = {};
}
@@ -917,11 +965,6 @@ jspb.Message.getRepeatedWrapperField = function(msg, ctor, fieldNumber) {
}
msg.wrappers_[fieldNumber] = wrappers;
}
- var val = msg.wrappers_[fieldNumber];
- if (val == jspb.Message.EMPTY_LIST_SENTINEL_) {
- val = msg.wrappers_[fieldNumber] = [];
- }
- return /** @type {Array<!jspb.Message>} */ (val);
};
@@ -981,6 +1024,48 @@ jspb.Message.setRepeatedWrapperField = function(msg, fieldNumber, value) {
/**
+ * Add a message to a repeated proto field.
+ * @param {!jspb.Message} msg A jspb proto.
+ * @param {number} fieldNumber The field number.
+ * @param {T_CHILD|undefined} value Proto that will be added to the
+ * repeated field.
+ * @param {function(new:T_CHILD, ?Array=)} ctor The constructor of the
+ * message type.
+ * @param {number|undefined} index Index at which to insert the value.
+ * @return {T_CHILD_NOT_UNDEFINED} proto that was inserted to the repeated field
+ * @template MessageType
+ * Use go/closure-ttl to declare a non-undefined version of T_CHILD. Replace the
+ * undefined in blah|undefined with none. This is necessary because the compiler
+ * will infer T_CHILD to be |undefined.
+ * @template T_CHILD
+ * @template T_CHILD_NOT_UNDEFINED :=
+ * cond(isUnknown(T_CHILD), unknown(),
+ * mapunion(T_CHILD, (X) =>
+ * cond(eq(X, 'undefined'), none(), X)))
+ * =:
+ * @protected
+ */
+jspb.Message.addToRepeatedWrapperField = function(
+ msg, fieldNumber, value, ctor, index) {
+ jspb.Message.wrapRepeatedField_(msg, ctor, fieldNumber);
+ var wrapperArray = msg.wrappers_[fieldNumber];
+ if (!wrapperArray) {
+ wrapperArray = msg.wrappers_[fieldNumber] = [];
+ }
+ var insertedValue = value ? value : new ctor();
+ var array = jspb.Message.getField(msg, fieldNumber);
+ if (index != undefined) {
+ wrapperArray.splice(index, 0, insertedValue);
+ array.splice(index, 0, insertedValue.toArray());
+ } else {
+ wrapperArray.push(insertedValue);
+ array.push(insertedValue.toArray());
+ }
+ return insertedValue;
+};
+
+
+/**
* Converts a JsPb repeated message field into a map. The map will contain
* protos unless an optional toObject function is given, in which case it will
* contain objects suitable for Soy rendering.
@@ -1114,32 +1199,39 @@ jspb.Message.prototype.getExtension = function(fieldInfo) {
* @param {jspb.ExtensionFieldInfo} fieldInfo Specifies the field to set.
* @param {jspb.Message|string|Uint8Array|number|boolean|Array?} value The value
* to set.
+ * @return {THIS} For chaining
+ * @this {THIS}
+ * @template THIS
*/
jspb.Message.prototype.setExtension = function(fieldInfo, value) {
- if (!this.wrappers_) {
- this.wrappers_ = {};
+ // Cast self, since the inferred THIS is unknown inside the function body.
+ // https://github.com/google/closure-compiler/issues/1411#issuecomment-232442220
+ var self = /** @type {!jspb.Message} */ (this);
+ if (!self.wrappers_) {
+ self.wrappers_ = {};
}
- jspb.Message.maybeInitEmptyExtensionObject_(this);
+ jspb.Message.maybeInitEmptyExtensionObject_(self);
var fieldNumber = fieldInfo.fieldIndex;
if (fieldInfo.isRepeated) {
value = value || [];
if (fieldInfo.isMessageType()) {
- this.wrappers_[fieldNumber] = value;
- this.extensionObject_[fieldNumber] = goog.array.map(
+ self.wrappers_[fieldNumber] = value;
+ self.extensionObject_[fieldNumber] = goog.array.map(
/** @type {Array<jspb.Message>} */ (value), function(msg) {
return msg.toArray();
});
} else {
- this.extensionObject_[fieldNumber] = value;
+ self.extensionObject_[fieldNumber] = value;
}
} else {
if (fieldInfo.isMessageType()) {
- this.wrappers_[fieldNumber] = value;
- this.extensionObject_[fieldNumber] = value ? value.toArray() : value;
+ self.wrappers_[fieldNumber] = value;
+ self.extensionObject_[fieldNumber] = value ? value.toArray() : value;
} else {
- this.extensionObject_[fieldNumber] = value;
+ self.extensionObject_[fieldNumber] = value;
}
}
+ return self;
};
@@ -1308,7 +1400,30 @@ jspb.Message.compareFields = function(field1, field2) {
/**
- * Static clone function. NOTE: A type-safe method called "cloneMessage" exists
+ * Templated, type-safe cloneMessage definition.
+ * @return {THIS}
+ * @this {THIS}
+ * @template THIS
+ */
+jspb.Message.prototype.cloneMessage = function() {
+ return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
+};
+
+/**
+ * Alias clone to cloneMessage. goog.object.unsafeClone uses clone to
+ * efficiently copy objects. Without this alias, copying jspb messages comes
+ * with a large performance penalty.
+ * @return {THIS}
+ * @this {THIS}
+ * @template THIS
+ */
+jspb.Message.prototype.clone = function() {
+ return jspb.Message.cloneMessage(/** @type {!jspb.Message} */ (this));
+};
+
+/**
+ * Static clone function. NOTE: A type-safe method called "cloneMessage"
+ * exists
* on each generated JsPb class. Do not call this function directly.
* @param {!jspb.Message} msg A message to clone.
* @return {!jspb.Message} A deep clone of the given message.
@@ -1429,3 +1544,4 @@ jspb.Message.registry_ = {};
* @type {!Object.<number, jspb.ExtensionFieldInfo>}
*/
jspb.Message.messageSetExtensions = {};
+jspb.Message.messageSetExtensionsBinary = {};
diff --git a/js/message_test.js b/js/message_test.js
index b7791431..b0a0a72e 100644
--- a/js/message_test.js
+++ b/js/message_test.js
@@ -269,7 +269,7 @@ describe('Message test suite', function() {
assertFalse(response.hasEnumField());
});
- it('testMessageRegistration', function() {
+ it('testMessageRegistration', /** @suppress {visibility} */ function() {
// goog.require(SomeResponse) will include its library, which will in
// turn add SomeResponse to the message registry.
assertEquals(jspb.Message.registry_['res'], proto.jspb.test.SomeResponse);
@@ -297,47 +297,9 @@ describe('Message test suite', function() {
var expected = [,,, [], []];
expected[0] = expected[1] = expected[2] = undefined;
assertObjectEquals(expected, foo.toArray());
-
- // Test set(null). We could deprecated this in favor of clear(), but
- // it's also convenient to have.
- data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
- foo = new proto.jspb.test.OptionalFields(data);
- foo.setAString(null);
- foo.setABool(null);
- foo.setANestedMessage(null);
- foo.setARepeatedMessageList(null);
- foo.setARepeatedStringList(null);
- assertEquals('', foo.getAString());
- assertEquals(false, foo.getABool());
- assertNull(foo.getANestedMessage());
- assertFalse(foo.hasAString());
- assertFalse(foo.hasABool());
- assertObjectEquals([], foo.getARepeatedMessageList());
- assertObjectEquals([], foo.getARepeatedStringList());
- assertObjectEquals([null, null, null, [], []], foo.toArray());
-
- // Test set(undefined). Again, not something we really need, and not
- // supported directly by our typing, but it should 'do the right thing'.
- data = ['str', true, [11], [[22], [33]], ['s1', 's2']];
- foo = new proto.jspb.test.OptionalFields(data);
- foo.setAString(undefined);
- foo.setABool(undefined);
- foo.setANestedMessage(undefined);
- foo.setARepeatedMessageList(undefined);
- foo.setARepeatedStringList(undefined);
- assertEquals('', foo.getAString());
- assertEquals(false, foo.getABool());
- assertUndefined(foo.getANestedMessage());
- assertFalse(foo.hasAString());
- assertFalse(foo.hasABool());
- assertObjectEquals([], foo.getARepeatedMessageList());
- assertObjectEquals([], foo.getARepeatedStringList());
- expected = [,,, [], []];
- expected[0] = expected[1] = expected[2] = undefined;
- assertObjectEquals(expected, foo.toArray());
});
- it('testDifferenceRawObject', function() {
+ it('testDifferenceRawObject', /** @suppress {visibility} */ function() {
var p1 = new proto.jspb.test.HasExtensions(['hi', 'diff', {}]);
var p2 = new proto.jspb.test.HasExtensions(['hi', 'what',
{1000: 'unique'}]);
@@ -477,7 +439,7 @@ describe('Message test suite', function() {
var extension = new proto.jspb.test.CloneExtension();
extension.setExt('e1');
original.setExtension(proto.jspb.test.IsExtension.extField, extension);
- var clone = original.cloneMessage();
+ var clone = original.clone();
assertArrayEquals(['v1',, ['x1', ['y1', 'z1']],,
[['x2', ['y2', 'z2']], ['x3', ['y3', 'z3']]], bytes1,, { 100: [, 'e1'] }],
clone.toArray());
@@ -712,11 +674,12 @@ describe('Message test suite', function() {
assertArrayEquals([1, 2, 3, {1: 'hi'}], msg.toArray());
});
- it('testExtendedMessageEnsureObject', function() {
- var data = new proto.jspb.test.HasExtensions(['str1',
- {'a_key': 'an_object'}]);
- assertEquals('an_object', data.extensionObject_['a_key']);
- });
+ it('testExtendedMessageEnsureObject',
+ /** @suppress {visibility} */ function() {
+ var data =
+ new proto.jspb.test.HasExtensions(['str1', {'a_key': 'an_object'}]);
+ assertEquals('an_object', data.extensionObject_['a_key']);
+ });
it('testToObject_hasExtensionField', function() {
var data = new proto.jspb.test.HasExtensions(['str1', {100: ['ext1']}]);
@@ -1077,4 +1040,18 @@ describe('Message test suite', function() {
assertNan(message.getDefaultDoubleField());
});
+ // Verify that we can successfully use a field referring to a nested message
+ // from a different .proto file.
+ it('testForeignNestedMessage', function() {
+ var msg = new proto.jspb.test.ForeignNestedFieldMessage();
+ var nested = new proto.jspb.test.Deeply.Nested.Message();
+ nested.setCount(5);
+ msg.setDeeplyNestedMessage(nested);
+
+ // After a serialization-deserialization round trip we should get back the
+ // same data we started with.
+ var serialized = msg.serializeBinary();
+ var deserialized = proto.jspb.test.ForeignNestedFieldMessage.deserializeBinary(serialized);
+ assertEquals(5, deserialized.getDeeplyNestedMessage().getCount());
+ });
});
diff --git a/js/package.json b/js/package.json
index 3f51d96b..d3c77eb6 100644
--- a/js/package.json
+++ b/js/package.json
@@ -1,6 +1,6 @@
{
"name": "google-protobuf",
- "version": "3.0.0",
+ "version": "3.1.0",
"description": "Protocol Buffers for JavaScript",
"main": "google-protobuf.js",
"files": [
@@ -22,5 +22,5 @@
"url": "https://github.com/google/protobuf/tree/master/js"
},
"author": "Google Protocol Buffers Team",
- "license": "Apache-2.0"
+ "license" : "BSD-3-Clause"
}
diff --git a/js/proto3_test.js b/js/proto3_test.js
index fab0fd44..3c929eff 100644
--- a/js/proto3_test.js
+++ b/js/proto3_test.js
@@ -294,7 +294,7 @@ describe('proto3Test', function() {
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_BAR);
msg.setOptionalForeignEnum(proto.jspb.test.Proto3Enum.PROTO3_FOO);
msg.setOneofUint32(32);
- msg.setOneofUint32(null);
+ msg.clearOneofUint32();
var serialized = msg.serializeBinary();
diff --git a/js/test.proto b/js/test.proto
index 937ffb89..db238e1a 100644
--- a/js/test.proto
+++ b/js/test.proto
@@ -234,3 +234,37 @@ message TestEndsWithBytes {
optional bytes data = 2;
}
+message TestMapFieldsNoBinary {
+ map<string, string> map_string_string = 1;
+ map<string, int32> map_string_int32 = 2;
+ map<string, int64> map_string_int64 = 3;
+ map<string, bool> map_string_bool = 4;
+ map<string, double> map_string_double = 5;
+ map<string, MapValueEnumNoBinary> map_string_enum = 6;
+ map<string, MapValueMessageNoBinary> map_string_msg = 7;
+
+ map<int32, string> map_int32_string = 8;
+ map<int64, string> map_int64_string = 9;
+ map<bool, string> map_bool_string = 10;
+
+ optional TestMapFieldsNoBinary test_map_fields = 11;
+ map<string, TestMapFieldsNoBinary> map_string_testmapfields = 12;
+}
+
+enum MapValueEnumNoBinary {
+ MAP_VALUE_FOO_NOBINARY = 0;
+ MAP_VALUE_BAR_NOBINARY = 1;
+ MAP_VALUE_BAZ_NOBINARY = 2;
+}
+
+message MapValueMessageNoBinary {
+ optional int32 foo = 1;
+}
+
+message Deeply {
+ message Nested {
+ message Message {
+ optional int32 count = 1;
+ }
+ }
+}
diff --git a/js/test2.proto b/js/test2.proto
index 44e55eff..b67f93fa 100644
--- a/js/test2.proto
+++ b/js/test2.proto
@@ -35,6 +35,8 @@ option java_multiple_files = true;
package jspb.test;
+import "test.proto";
+
message TestExtensionsMessage {
optional int32 intfield = 1;
extensions 100 to max;
@@ -52,3 +54,7 @@ extend TestExtensionsMessage {
optional ExtensionMessage floating_msg_field = 101;
optional string floating_str_field = 102;
}
+
+message ForeignNestedFieldMessage {
+ optional Deeply.Nested.Message deeply_nested_message = 1;
+}
diff --git a/objectivec/DevTools/check_version_stamps.sh b/objectivec/DevTools/check_version_stamps.sh
index 325b71dd..1acbe2a2 100755
--- a/objectivec/DevTools/check_version_stamps.sh
+++ b/objectivec/DevTools/check_version_stamps.sh
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/bin/bash -eu
# This script checks that the runtime version number constant in the compiler
# source and in the runtime source is the same.
@@ -8,8 +8,6 @@
# builds would break. At the same time, we don't want the runtime source
# depending on the compiler sources; so two copies of the constant are needed.
-set -eu
-
readonly ScriptDir=$(dirname "$(echo $0 | sed -e "s,^\([^/]\),$(pwd)/\1,")")
readonly ProtoRootDir="${ScriptDir}/../.."
@@ -18,39 +16,40 @@ die() {
exit 1
}
-readonly ConstantName=GOOGLE_PROTOBUF_OBJC_GEN_VERSION
-
-# Collect version from plugin sources.
-
-readonly PluginSrc="${ProtoRootDir}/src/google/protobuf/compiler/objectivec/objectivec_file.cc"
-readonly PluginVersion=$( \
- cat "${PluginSrc}" \
- | sed -n -e "s:const int32 ${ConstantName} = \([0-9]*\);:\1:p"
-)
-
-if [[ -z "${PluginVersion}" ]] ; then
- die "Failed to find ${ConstantName} in the plugin source (${PluginSrc})."
-fi
-
-# Collect version from runtime sources.
-
+readonly GeneratorSrc="${ProtoRootDir}/src/google/protobuf/compiler/objectivec/objectivec_file.cc"
readonly RuntimeSrc="${ProtoRootDir}/objectivec/GPBBootstrap.h"
-readonly RuntimeVersion=$( \
- cat "${RuntimeSrc}" \
- | sed -n -e "s:#define ${ConstantName} \([0-9]*\):\1:p"
-)
-
-if [[ -z "${RuntimeVersion}" ]] ; then
- die "Failed to find ${ConstantName} in the runtime source (${RuntimeSrc})."
-fi
-
-# Compare them.
-if [[ "${PluginVersion}" != "${RuntimeVersion}" ]] ; then
- die "Versions don't match!
- Plugin: ${PluginVersion} from ${PluginSrc}
- Runtime: ${RuntimeVersion} from ${RuntimeSrc}
+check_constant() {
+ local ConstantName="$1"
+
+ # Collect version from generator sources.
+ local GeneratorVersion=$( \
+ cat "${GeneratorSrc}" \
+ | sed -n -e "s:const int32 ${ConstantName} = \([0-9]*\);:\1:p"
+ )
+ if [[ -z "${GeneratorVersion}" ]] ; then
+ die "Failed to find ${ConstantName} in the generator source (${GeneratorSrc})."
+ fi
+
+ # Collect version from runtime sources.
+ local RuntimeVersion=$( \
+ cat "${RuntimeSrc}" \
+ | sed -n -e "s:#define ${ConstantName} \([0-9]*\):\1:p"
+ )
+ if [[ -z "${RuntimeVersion}" ]] ; then
+ die "Failed to find ${ConstantName} in the runtime source (${RuntimeSrc})."
+ fi
+
+ # Compare them.
+ if [[ "${GeneratorVersion}" != "${RuntimeVersion}" ]] ; then
+ die "${ConstantName} values don't match!
+ Generator: ${GeneratorVersion} from ${GeneratorSrc}
+ Runtime: ${RuntimeVersion} from ${RuntimeSrc}
"
-fi
+ fi
+}
+
+# Do the check.
+check_constant GOOGLE_PROTOBUF_OBJC_VERSION
# Success
diff --git a/objectivec/DevTools/compile_testing_protos.sh b/objectivec/DevTools/compile_testing_protos.sh
index 82953130..6cc32da9 100755
--- a/objectivec/DevTools/compile_testing_protos.sh
+++ b/objectivec/DevTools/compile_testing_protos.sh
@@ -1,17 +1,16 @@
-#!/bin/bash
-
+#!/bin/bash -eu
# Invoked by the Xcode projects to build the protos needed for the unittests.
-set -eu
-
readonly OUTPUT_DIR="${PROJECT_DERIVED_FILE_DIR}/protos"
+# -----------------------------------------------------------------------------
# Helper for bailing.
die() {
echo "Error: $1"
exit 2
}
+# -----------------------------------------------------------------------------
# What to do.
case "${ACTION}" in
"")
@@ -26,12 +25,19 @@ case "${ACTION}" in
;;
esac
-# Move to the top of the protobuf directories.
-cd "${SRCROOT}/.."
+# -----------------------------------------------------------------------------
+# Ensure the output dir exists
+mkdir -p "${OUTPUT_DIR}/google/protobuf"
+# -----------------------------------------------------------------------------
+# Move to the top of the protobuf directories and ensure there is a protoc
+# binary to use.
+cd "${SRCROOT}/.."
[[ -x src/protoc ]] || \
die "Could not find the protoc binary; make sure you have built it (objectivec/DevTools/full_mac_build.sh -h)."
+# -----------------------------------------------------------------------------
+# See the compiler or proto files have changed.
RUN_PROTOC=no
if [[ ! -d "${OUTPUT_DIR}" ]] ; then
RUN_PROTOC=yes
@@ -50,7 +56,7 @@ else
# Find the oldest output file.
readonly OldestOutput=$(find \
"${OUTPUT_DIR}" \
- -type f -print0 \
+ -type f -name "*pbobjc.[hm]" -print0 \
| xargs -0 stat -f "%m %N" \
| sort -n -r | tail -n1 | cut -f2- -d" ")
# If the newest input is newer than the oldest output, regenerate.
@@ -64,10 +70,30 @@ if [[ "${RUN_PROTOC}" != "yes" ]] ; then
exit 0
fi
-# Ensure the output dir exists
-mkdir -p "${OUTPUT_DIR}/google/protobuf"
+# -----------------------------------------------------------------------------
+# Prune out all the files from previous generations to ensure we only have
+# current ones.
+find "${OUTPUT_DIR}" \
+ -type f -name "*pbobjc.[hm]" -print0 \
+ | xargs -0 rm -rf
+
+# -----------------------------------------------------------------------------
+# Helper to invoke protoc
+compile_protos() {
+ src/protoc \
+ --objc_out="${OUTPUT_DIR}/google/protobuf" \
+ --proto_path=src/google/protobuf/ \
+ --proto_path=src \
+ "$@"
+}
+
+# -----------------------------------------------------------------------------
+# Generate most of the proto files that exist in the C++ src tree. Several
+# are used in the tests, but the extra don't hurt in that they ensure ObjC
+# sources can be generated from them.
CORE_PROTO_FILES=(
+ src/google/protobuf/any_test.proto
src/google/protobuf/unittest_arena.proto
src/google/protobuf/unittest_custom_options.proto
src/google/protobuf/unittest_enormous_descriptor.proto
@@ -90,35 +116,32 @@ CORE_PROTO_FILES=(
src/google/protobuf/map_lite_unittest.proto
src/google/protobuf/map_proto2_unittest.proto
src/google/protobuf/map_unittest.proto
-)
-
-# The unittest_custom_options.proto extends the messages in descriptor.proto
-# so we build it in to test extending in general. The library doesn't provide
-# a descriptor as it doesn't use the classes/enums.
-CORE_PROTO_FILES+=(
+ # The unittest_custom_options.proto extends the messages in descriptor.proto
+ # so we build it in to test extending in general. The library doesn't provide
+ # a descriptor as it doesn't use the classes/enums.
src/google/protobuf/descriptor.proto
)
-compile_proto() {
- src/protoc \
- --objc_out="${OUTPUT_DIR}/google/protobuf" \
- --proto_path=src/google/protobuf/ \
- --proto_path=src \
- $*
-}
-
+# Note: there is overlap in package.Message names between some of the test
+# files, so they can't be generated all at once. This works because the overlap
+# isn't linked into a single binary.
for a_proto in "${CORE_PROTO_FILES[@]}" ; do
- compile_proto "${a_proto}"
+ compile_protos "${a_proto}"
done
-OBJC_PROTO_FILES=(
- objectivec/Tests/unittest_cycle.proto
- objectivec/Tests/unittest_runtime_proto2.proto
- objectivec/Tests/unittest_runtime_proto3.proto
- objectivec/Tests/unittest_objc.proto
+# -----------------------------------------------------------------------------
+# Generate the Objective C specific testing protos.
+compile_protos \
+ --proto_path="objectivec/Tests" \
+ objectivec/Tests/unittest_cycle.proto \
+ objectivec/Tests/unittest_extension_chain_a.proto \
+ objectivec/Tests/unittest_extension_chain_b.proto \
+ objectivec/Tests/unittest_extension_chain_c.proto \
+ objectivec/Tests/unittest_extension_chain_d.proto \
+ objectivec/Tests/unittest_extension_chain_e.proto \
+ objectivec/Tests/unittest_extension_chain_f.proto \
+ objectivec/Tests/unittest_extension_chain_g.proto \
+ objectivec/Tests/unittest_runtime_proto2.proto \
+ objectivec/Tests/unittest_runtime_proto3.proto \
+ objectivec/Tests/unittest_objc.proto \
objectivec/Tests/unittest_objc_startup.proto
-)
-
-for a_proto in "${OBJC_PROTO_FILES[@]}" ; do
- compile_proto --proto_path="objectivec/Tests" "${a_proto}"
-done
diff --git a/objectivec/DevTools/full_mac_build.sh b/objectivec/DevTools/full_mac_build.sh
index 89240ee0..7b335618 100755
--- a/objectivec/DevTools/full_mac_build.sh
+++ b/objectivec/DevTools/full_mac_build.sh
@@ -228,34 +228,23 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then
# NOTE: Different Xcode have different simulated hardware/os support.
readonly XCODE_VERSION_LINE="$(xcodebuild -version | grep Xcode\ )"
readonly XCODE_VERSION="${XCODE_VERSION_LINE/Xcode /}" # drop the prefix.
- IOS_SIMULATOR_NAME="Simulator"
case "${XCODE_VERSION}" in
6.* )
- echo "ERROR: Xcode 6.3/6.4 no longer supported for building, please use 7.0 or higher." 1>&2
+ echo "ERROR: Xcode 6.3/6.4 no longer supported for building, please use 8.0 or higher." 1>&2
exit 10
;;
- 7.1* )
- XCODEBUILD_TEST_BASE_IOS+=(
- -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPhone 6,OS=9.0" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPad Air,OS=9.0" # 64bit
- )
+ 7.* )
+ echo "ERROR: The unittests include Swift code that is now Swift 3.0." 1>&2
+ echo "ERROR: Xcode 8.0 or higher is required to build the test suite, but the library works with Xcode 7.x." 1>&2
+ exit 11
;;
- 7.2* )
+ 8.0* )
+ # The 8.* device seem to hang and never start under Xcode 8.
XCODEBUILD_TEST_BASE_IOS+=(
- -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPhone 6,OS=9.2" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPad Air,OS=9.2" # 64bit
- )
- ;;
- 7.3* )
- XCODEBUILD_TEST_BASE_IOS+=(
- -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPhone 6,OS=9.3" # 64bit
- -destination "platform=iOS Simulator,name=iPad 2,OS=8.1" # 32bit
- -destination "platform=iOS Simulator,name=iPad Air,OS=9.3" # 64bit
+ -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
)
;;
* )
@@ -272,7 +261,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 "${IOS_SIMULATOR_NAME}"
+ killall Simulator
fi
if [[ "${DO_XCODE_OSX_TESTS}" == "yes" ]] ; then
XCODEBUILD_TEST_BASE_OSX=(
@@ -282,6 +271,19 @@ if [[ "${DO_XCODE_OSX_TESTS}" == "yes" ]] ; then
# Since the ObjC 2.0 Runtime is required, 32bit OS X isn't supported.
-destination "platform=OS X,arch=x86_64" # 64bit
)
+ readonly XCODE_VERSION_LINE="$(xcodebuild -version | grep Xcode\ )"
+ readonly XCODE_VERSION="${XCODE_VERSION_LINE/Xcode /}" # drop the prefix.
+ case "${XCODE_VERSION}" in
+ 6.* )
+ echo "ERROR: Xcode 6.3/6.4 no longer supported for building, please use 8.0 or higher." 1>&2
+ exit 10
+ ;;
+ 7.* )
+ echo "ERROR: The unittests include Swift code that is now Swift 3.0." 1>&2
+ echo "ERROR: Xcode 8.0 or higher is required to build the test suite, but the library works with Xcode 7.x." 1>&2
+ exit 11
+ ;;
+ esac
if [[ "${DO_XCODE_DEBUG}" == "yes" ]] ; then
header "Doing Xcode OS X build/tests - Debug"
"${XCODEBUILD_TEST_BASE_OSX[@]}" -configuration Debug test
diff --git a/objectivec/GPBArray.h b/objectivec/GPBArray.h
index afda57f3..781cfb6f 100644
--- a/objectivec/GPBArray.h
+++ b/objectivec/GPBArray.h
@@ -32,11 +32,6 @@
#import "GPBRuntimeTypes.h"
-// These classes are used for repeated fields of basic data types. They are used because
-// they perform better than boxing into NSNumbers in NSArrays.
-
-// Note: These are not meant to be subclassed.
-
NS_ASSUME_NONNULL_BEGIN
//%PDDM-EXPAND DECLARE_ARRAYS()
@@ -44,39 +39,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Int32
+/**
+ * Class used for repeated fields of int32_t values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32Array : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBInt32Array.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBInt32Array with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBInt32Array with value in it.
+ **/
+ (instancetype)arrayWithValue:(int32_t)value;
+
+/**
+ * Creates and initializes a GPBInt32Array with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBInt32Array with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBInt32Array *)array;
+
+/**
+ * Creates and initializes a GPBInt32Array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBInt32Array with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBInt32Array.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBInt32Array with a copy of the values.
+ **/
- (instancetype)initWithValues:(const int32_t [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBInt32Array with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBInt32Array *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBInt32Array with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (int32_t)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(int32_t)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const int32_t [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBInt32Array *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(int32_t)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -84,39 +211,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - UInt32
+/**
+ * Class used for repeated fields of uint32_t values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32Array : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBUInt32Array.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBUInt32Array with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBUInt32Array with value in it.
+ **/
+ (instancetype)arrayWithValue:(uint32_t)value;
+
+/**
+ * Creates and initializes a GPBUInt32Array with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBUInt32Array with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBUInt32Array *)array;
+
+/**
+ * Creates and initializes a GPBUInt32Array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBUInt32Array with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBUInt32Array.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBUInt32Array with a copy of the values.
+ **/
- (instancetype)initWithValues:(const uint32_t [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBUInt32Array with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBUInt32Array *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBUInt32Array with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (uint32_t)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(uint32_t)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const uint32_t [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBUInt32Array *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(uint32_t)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint32_t)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -124,39 +383,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Int64
+/**
+ * Class used for repeated fields of int64_t values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64Array : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBInt64Array.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBInt64Array with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBInt64Array with value in it.
+ **/
+ (instancetype)arrayWithValue:(int64_t)value;
+
+/**
+ * Creates and initializes a GPBInt64Array with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBInt64Array with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBInt64Array *)array;
+
+/**
+ * Creates and initializes a GPBInt64Array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBInt64Array with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBInt64Array.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBInt64Array with a copy of the values.
+ **/
- (instancetype)initWithValues:(const int64_t [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBInt64Array with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBInt64Array *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBInt64Array with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (int64_t)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(int64_t)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const int64_t [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBInt64Array *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(int64_t)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int64_t)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -164,39 +555,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - UInt64
+/**
+ * Class used for repeated fields of uint64_t values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64Array : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBUInt64Array.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBUInt64Array with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBUInt64Array with value in it.
+ **/
+ (instancetype)arrayWithValue:(uint64_t)value;
+
+/**
+ * Creates and initializes a GPBUInt64Array with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBUInt64Array with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBUInt64Array *)array;
+
+/**
+ * Creates and initializes a GPBUInt64Array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBUInt64Array with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBUInt64Array.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBUInt64Array with a copy of the values.
+ **/
- (instancetype)initWithValues:(const uint64_t [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBUInt64Array with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBUInt64Array *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBUInt64Array with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (uint64_t)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(uint64_t)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const uint64_t [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBUInt64Array *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(uint64_t)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(uint64_t)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -204,39 +727,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Float
+/**
+ * Class used for repeated fields of float values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBFloatArray : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBFloatArray.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBFloatArray with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBFloatArray with value in it.
+ **/
+ (instancetype)arrayWithValue:(float)value;
+
+/**
+ * Creates and initializes a GPBFloatArray with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBFloatArray with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBFloatArray *)array;
+
+/**
+ * Creates and initializes a GPBFloatArray with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBFloatArray with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBFloatArray.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBFloatArray with a copy of the values.
+ **/
- (instancetype)initWithValues:(const float [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBFloatArray with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBFloatArray *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBFloatArray with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (float)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(float)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const float [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBFloatArray *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(float)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(float)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -244,39 +899,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Double
+/**
+ * Class used for repeated fields of double values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBDoubleArray : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBDoubleArray.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBDoubleArray with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBDoubleArray with value in it.
+ **/
+ (instancetype)arrayWithValue:(double)value;
+
+/**
+ * Creates and initializes a GPBDoubleArray with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBDoubleArray with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBDoubleArray *)array;
+
+/**
+ * Creates and initializes a GPBDoubleArray with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBDoubleArray with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBDoubleArray.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBDoubleArray with a copy of the values.
+ **/
- (instancetype)initWithValues:(const double [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBDoubleArray with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBDoubleArray *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBDoubleArray with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (double)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(double)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const double [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBDoubleArray *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(double)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(double)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -284,39 +1071,171 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Bool
+/**
+ * Class used for repeated fields of BOOL values. This performs better than
+ * boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolArray : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty GPBBoolArray.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBBoolArray with the single element given.
+ *
+ * @param value The value to be placed in the array.
+ *
+ * @return A newly instanced GPBBoolArray with value in it.
+ **/
+ (instancetype)arrayWithValue:(BOOL)value;
+
+/**
+ * Creates and initializes a GPBBoolArray with the contents of the given
+ * array.
+ *
+ * @param array Array with the contents to be put into the new array.
+ *
+ * @return A newly instanced GPBBoolArray with the contents of array.
+ **/
+ (instancetype)arrayWithValueArray:(GPBBoolArray *)array;
+
+/**
+ * Creates and initializes a GPBBoolArray with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBBoolArray with a capacity of count.
+ **/
+ (instancetype)arrayWithCapacity:(NSUInteger)count;
+/**
+ * @return A newly initialized and empty GPBBoolArray.
+ **/
- (instancetype)init NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBBoolArray with a copy of the values.
+ **/
- (instancetype)initWithValues:(const BOOL [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBBoolArray with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBBoolArray *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBBoolArray with a capacity of count.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)count;
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (BOOL)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block;
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(BOOL)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const BOOL [])values count:(NSUInteger)count;
+
+/**
+ * Adds the values from the given array to this array.
+ *
+ * @param array The array containing the elements to add to this array.
+ **/
- (void)addValuesFromArray:(GPBBoolArray *)array;
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(BOOL)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(BOOL)value;
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -324,27 +1243,108 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Enum
+/**
+ * This class is used for repeated fields of int32_t values. This performs
+ * better than boxing into NSNumbers in NSArrays.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBEnumArray : NSObject <NSCopying>
+/** The number of elements contained in the array. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty GPBEnumArray.
+ **/
+ (instancetype)array;
+
+/**
+ * Creates and initializes a GPBEnumArray with the enum validation function
+ * given.
+ *
+ * @param func The enum validation function for the array.
+ *
+ * @return A newly instanced GPBEnumArray.
+ **/
+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a GPBEnumArray with the enum validation function
+ * given and the single raw value given.
+ *
+ * @param func The enum validation function for the array.
+ * @param value The raw value to add to this array.
+ *
+ * @return A newly instanced GPBEnumArray.
+ **/
+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)value;
+
+/**
+ * Creates and initializes a GPBEnumArray that adds the elements from the
+ * given array.
+ *
+ * @param array Array containing the values to add to the new array.
+ *
+ * @return A newly instanced GPBEnumArray.
+ **/
+ (instancetype)arrayWithValueArray:(GPBEnumArray *)array;
+
+/**
+ * Creates and initializes a GPBEnumArray with the given enum validation
+ * function and with the givencapacity.
+ *
+ * @param func The enum validation function for the array.
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly instanced GPBEnumArray with a capacity of count.
+ **/
+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)count;
+/**
+ * Initializes the array with the given enum validation function.
+ *
+ * @param func The enum validation function for the array.
+ *
+ * @return A newly initialized GPBEnumArray with a copy of the values.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
NS_DESIGNATED_INITIALIZER;
-// Initializes the array, copying the values.
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param func The enum validation function for the array.
+ * @param values An array with the values to put inside this array.
+ * @param count The number of elements to copy into the array.
+ *
+ * @return A newly initialized GPBEnumArray with a copy of the values.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
count:(NSUInteger)count;
+
+/**
+ * Initializes the array, copying the given values.
+ *
+ * @param array An array with the values to put inside this array.
+ *
+ * @return A newly initialized GPBEnumArray with a copy of the values.
+ **/
- (instancetype)initWithValueArray:(GPBEnumArray *)array;
+
+/**
+ * Initializes the array with the given capacity.
+ *
+ * @param func The enum validation function for the array.
+ * @param count The capacity needed for the array.
+ *
+ * @return A newly initialized GPBEnumArray with a capacity of count.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)count;
@@ -352,18 +1352,68 @@ NS_ASSUME_NONNULL_BEGIN
// valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
+/**
+ * Gets the value at the given index.
+ *
+ * @param index The index of the value to get.
+ *
+ * @return The value at the given index.
+ **/
- (int32_t)valueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block;
// These methods bypass the validationFunc to provide access to values that were not
// known at the time the binary was compiled.
+/**
+ * Gets the raw enum value at the given index.
+ *
+ * @param index The index of the raw enum value to get.
+ *
+ * @return The raw enum value at the given index.
+ **/
- (int32_t)rawValueAtIndex:(NSUInteger)index;
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateRawValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block;
+
+/**
+ * Enumerates the values on this array with the given block.
+ *
+ * @param opts Options to control the enumeration.
+ * @param block The block to enumerate with.
+ * **value**: The current value being enumerated.
+ * **idx**: The index of the current value.
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts
usingBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block;
@@ -372,29 +1422,114 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Adds a value to this array.
+ *
+ * @param value The value to add to this array.
+ **/
- (void)addValue:(int32_t)value;
+
+/**
+ * Adds values to this array.
+ *
+ * @param values The values to add to this array.
+ * @param count The number of elements to add.
+ **/
- (void)addValues:(const int32_t [])values count:(NSUInteger)count;
+
+/**
+ * Inserts a value into the given position.
+ *
+ * @param value The value to add to this array.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertValue:(int32_t)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the value at the given index with the given value.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withValue:(int32_t)value;
// These methods bypass the validationFunc to provide setting of values that were not
// known at the time the binary was compiled.
+/**
+ * Adds a raw enum value to this array.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param value The raw enum value to add to the array.
+ **/
- (void)addRawValue:(int32_t)value;
+
+/**
+ * Adds raw enum values to this array.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param array Array containing the raw enum values to add to this array.
+ **/
- (void)addRawValuesFromArray:(GPBEnumArray *)array;
+
+/**
+ * Adds raw enum values to this array.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param values Array containing the raw enum values to add to this array.
+ * @param count The number of raw values to add.
+ **/
- (void)addRawValues:(const int32_t [])values count:(NSUInteger)count;
+/**
+ * Inserts a raw enum value at the given index.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param value Raw enum value to add.
+ * @param index The index into which to insert the value.
+ **/
- (void)insertRawValue:(int32_t)value atIndex:(NSUInteger)index;
+/**
+ * Replaces the raw enum value at the given index with the given value.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param index The index for which to replace the value.
+ * @param value The raw enum value to replace with.
+ **/
- (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(int32_t)value;
// No validation applies to these methods.
+/**
+ * Removes the value at the given index.
+ *
+ * @param index The index of the value to remove.
+ **/
- (void)removeValueAtIndex:(NSUInteger)index;
+
+/**
+ * Removes all the values from this array.
+ **/
- (void)removeAll;
+/**
+ * Exchanges the values between the given indexes.
+ *
+ * @param idx1 The index of the first element to exchange.
+ * @param idx2 The index of the second element to exchange.
+ **/
- (void)exchangeValueAtIndex:(NSUInteger)idx1
withValueAtIndex:(NSUInteger)idx2;
@@ -421,20 +1556,82 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE ARRAY_INTERFACE_SIMPLE(NAME, TYPE)
//%#pragma mark - NAME
//%
+//%/**
+//% * Class used for repeated fields of ##TYPE## values. This performs better than
+//% * boxing into NSNumbers in NSArrays.
+//% *
+//% * @note This class is not meant to be subclassed.
+//% **/
//%@interface GPB##NAME##Array : NSObject <NSCopying>
//%
+//%/** The number of elements contained in the array. */
//%@property(nonatomic, readonly) NSUInteger count;
//%
+//%/**
+//% * @return A newly instanced and empty GPB##NAME##Array.
+//% **/
//%+ (instancetype)array;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array with the single element given.
+//% *
+//% * @param value The value to be placed in the array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array with value in it.
+//% **/
//%+ (instancetype)arrayWithValue:(TYPE)value;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array with the contents of the given
+//% * array.
+//% *
+//% * @param array Array with the contents to be put into the new array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array with the contents of array.
+//% **/
//%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array with the given capacity.
+//% *
+//% * @param count The capacity needed for the array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array with a capacity of count.
+//% **/
//%+ (instancetype)arrayWithCapacity:(NSUInteger)count;
//%
+//%/**
+//% * @return A newly initialized and empty GPB##NAME##Array.
+//% **/
//%- (instancetype)init NS_DESIGNATED_INITIALIZER;
-//%// Initializes the array, copying the values.
+//%
+//%/**
+//% * Initializes the array, copying the given values.
+//% *
+//% * @param values An array with the values to put inside this array.
+//% * @param count The number of elements to copy into the array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
+//% **/
//%- (instancetype)initWithValues:(const TYPE [])values
//% count:(NSUInteger)count;
+//%
+//%/**
+//% * Initializes the array, copying the given values.
+//% *
+//% * @param array An array with the values to put inside this array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
+//% **/
//%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array;
+//%
+//%/**
+//% * Initializes the array with the given capacity.
+//% *
+//% * @param count The capacity needed for the array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a capacity of count.
+//% **/
//%- (instancetype)initWithCapacity:(NSUInteger)count;
//%
//%ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, Basic)
@@ -451,27 +1648,108 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE ARRAY_INTERFACE_ENUM(NAME, TYPE)
//%#pragma mark - NAME
//%
+//%/**
+//% * This class is used for repeated fields of ##TYPE## values. This performs
+//% * better than boxing into NSNumbers in NSArrays.
+//% *
+//% * @note This class is not meant to be subclassed.
+//% **/
//%@interface GPB##NAME##Array : NSObject <NSCopying>
//%
+//%/** The number of elements contained in the array. */
//%@property(nonatomic, readonly) NSUInteger count;
+//%/** The validation function to check if the enums are valid. */
//%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
//%
+//%/**
+//% * @return A newly instanced and empty GPB##NAME##Array.
+//% **/
//%+ (instancetype)array;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array with the enum validation function
+//% * given.
+//% *
+//% * @param func The enum validation function for the array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array.
+//% **/
//%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array with the enum validation function
+//% * given and the single raw value given.
+//% *
+//% * @param func The enum validation function for the array.
+//% * @param value The raw value to add to this array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array.
+//% **/
//%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% rawValue:(TYPE)value;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array that adds the elements from the
+//% * given array.
+//% *
+//% * @param array Array containing the values to add to the new array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array.
+//% **/
//%+ (instancetype)arrayWithValueArray:(GPB##NAME##Array *)array;
+//%
+//%/**
+//% * Creates and initializes a GPB##NAME##Array with the given enum validation
+//% * function and with the givencapacity.
+//% *
+//% * @param func The enum validation function for the array.
+//% * @param count The capacity needed for the array.
+//% *
+//% * @return A newly instanced GPB##NAME##Array with a capacity of count.
+//% **/
//%+ (instancetype)arrayWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% capacity:(NSUInteger)count;
//%
+//%/**
+//% * Initializes the array with the given enum validation function.
+//% *
+//% * @param func The enum validation function for the array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
+//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% NS_DESIGNATED_INITIALIZER;
//%
-//%// Initializes the array, copying the values.
+//%/**
+//% * Initializes the array, copying the given values.
+//% *
+//% * @param func The enum validation function for the array.
+//% * @param values An array with the values to put inside this array.
+//% * @param count The number of elements to copy into the array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
+//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% rawValues:(const TYPE [])values
//% count:(NSUInteger)count;
+//%
+//%/**
+//% * Initializes the array, copying the given values.
+//% *
+//% * @param array An array with the values to put inside this array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a copy of the values.
+//% **/
//%- (instancetype)initWithValueArray:(GPB##NAME##Array *)array;
+//%
+//%/**
+//% * Initializes the array with the given capacity.
+//% *
+//% * @param func The enum validation function for the array.
+//% * @param count The capacity needed for the array.
+//% *
+//% * @return A newly initialized GPB##NAME##Array with a capacity of count.
+//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% capacity:(NSUInteger)count;
//%
@@ -484,9 +1762,34 @@ NS_ASSUME_NONNULL_END
//%// These methods bypass the validationFunc to provide access to values that were not
//%// known at the time the binary was compiled.
//%
+//%/**
+//% * Gets the raw enum value at the given index.
+//% *
+//% * @param index The index of the raw enum value to get.
+//% *
+//% * @return The raw enum value at the given index.
+//% **/
//%- (TYPE)rawValueAtIndex:(NSUInteger)index;
//%
+//%/**
+//% * Enumerates the values on this array with the given block.
+//% *
+//% * @param block The block to enumerate with.
+//% * **value**: The current value being enumerated.
+//% * **idx**: The index of the current value.
+//% * **stop**: A pointer to a boolean that when set stops the enumeration.
+//% **/
//%- (void)enumerateRawValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block;
+//%
+//%/**
+//% * Enumerates the values on this array with the given block.
+//% *
+//% * @param opts Options to control the enumeration.
+//% * @param block The block to enumerate with.
+//% * **value**: The current value being enumerated.
+//% * **idx**: The index of the current value.
+//% * **stop**: A pointer to a boolean that when set stops the enumeration.
+//% **/
//%- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts
//% usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block;
//%
@@ -501,23 +1804,88 @@ NS_ASSUME_NONNULL_END
//%
//%PDDM-DEFINE ARRAY_IMMUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME)
+//%/**
+//% * Gets the value at the given index.
+//% *
+//% * @param index The index of the value to get.
+//% *
+//% * @return The value at the given index.
+//% **/
//%- (TYPE)valueAtIndex:(NSUInteger)index;
//%
+//%/**
+//% * Enumerates the values on this array with the given block.
+//% *
+//% * @param block The block to enumerate with.
+//% * **value**: The current value being enumerated.
+//% * **idx**: The index of the current value.
+//% * **stop**: A pointer to a boolean that when set stops the enumeration.
+//% **/
//%- (void)enumerateValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block;
+//%
+//%/**
+//% * Enumerates the values on this array with the given block.
+//% *
+//% * @param opts Options to control the enumeration.
+//% * @param block The block to enumerate with.
+//% * **value**: The current value being enumerated.
+//% * **idx**: The index of the current value.
+//% * **stop**: A pointer to a boolean that when set stops the enumeration.
+//% **/
//%- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
//% usingBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block;
//%PDDM-DEFINE ARRAY_MUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME)
+//%/**
+//% * Adds a value to this array.
+//% *
+//% * @param value The value to add to this array.
+//% **/
//%- (void)addValue:(TYPE)value;
+//%
+//%/**
+//% * Adds values to this array.
+//% *
+//% * @param values The values to add to this array.
+//% * @param count The number of elements to add.
+//% **/
//%- (void)addValues:(const TYPE [])values count:(NSUInteger)count;
+//%
//%ARRAY_EXTRA_MUTABLE_METHODS1_##HELPER_NAME(NAME, TYPE)
+//%/**
+//% * Inserts a value into the given position.
+//% *
+//% * @param value The value to add to this array.
+//% * @param index The index into which to insert the value.
+//% **/
//%- (void)insertValue:(TYPE)value atIndex:(NSUInteger)index;
//%
+//%/**
+//% * Replaces the value at the given index with the given value.
+//% *
+//% * @param index The index for which to replace the value.
+//% * @param value The value to replace with.
+//% **/
//%- (void)replaceValueAtIndex:(NSUInteger)index withValue:(TYPE)value;
//%ARRAY_EXTRA_MUTABLE_METHODS2_##HELPER_NAME(NAME, TYPE)
+//%/**
+//% * Removes the value at the given index.
+//% *
+//% * @param index The index of the value to remove.
+//% **/
//%- (void)removeValueAtIndex:(NSUInteger)index;
+//%
+//%/**
+//% * Removes all the values from this array.
+//% **/
//%- (void)removeAll;
//%
+//%/**
+//% * Exchanges the values between the given indexes.
+//% *
+//% * @param idx1 The index of the first element to exchange.
+//% * @param idx2 The index of the second element to exchange.
+//% **/
//%- (void)exchangeValueAtIndex:(NSUInteger)idx1
//% withValueAtIndex:(NSUInteger)idx2;
@@ -526,6 +1894,11 @@ NS_ASSUME_NONNULL_END
//
//%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS1_Basic(NAME, TYPE)
+//%/**
+//% * Adds the values from the given array to this array.
+//% *
+//% * @param array The array containing the elements to add to this array.
+//% **/
//%- (void)addValuesFromArray:(GPB##NAME##Array *)array;
//%
//%PDDM-DEFINE ARRAY_EXTRA_MUTABLE_METHODS2_Basic(NAME, TYPE)
@@ -537,12 +1910,57 @@ NS_ASSUME_NONNULL_END
//%// These methods bypass the validationFunc to provide setting of values that were not
//%// known at the time the binary was compiled.
//%
+//%/**
+//% * Adds a raw enum value to this array.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param value The raw enum value to add to the array.
+//% **/
//%- (void)addRawValue:(TYPE)value;
+//%
+//%/**
+//% * Adds raw enum values to this array.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param array Array containing the raw enum values to add to this array.
+//% **/
//%- (void)addRawValuesFromArray:(GPB##NAME##Array *)array;
+//%
+//%/**
+//% * Adds raw enum values to this array.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param values Array containing the raw enum values to add to this array.
+//% * @param count The number of raw values to add.
+//% **/
//%- (void)addRawValues:(const TYPE [])values count:(NSUInteger)count;
//%
+//%/**
+//% * Inserts a raw enum value at the given index.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param value Raw enum value to add.
+//% * @param index The index into which to insert the value.
+//% **/
//%- (void)insertRawValue:(TYPE)value atIndex:(NSUInteger)index;
//%
+//%/**
+//% * Replaces the raw enum value at the given index with the given value.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param index The index for which to replace the value.
+//% * @param value The raw enum value to replace with.
+//% **/
//%- (void)replaceValueAtIndex:(NSUInteger)index withRawValue:(TYPE)value;
//%
//%// No validation applies to these methods.
diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m
index 64869bbb..ae57747d 100644
--- a/objectivec/GPBArray.m
+++ b/objectivec/GPBArray.m
@@ -195,7 +195,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
//%}
//%
//%- (void)enumerate##ACCESSOR_NAME##ValuesWithBlock:(void (^)(TYPE value, NSUInteger idx, BOOL *stop))block {
-//% [self enumerate##ACCESSOR_NAME##ValuesWithOptions:0 usingBlock:block];
+//% [self enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
//%}
//%
//%- (void)enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)opts
@@ -406,7 +406,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -654,7 +654,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(uint32_t value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -902,7 +902,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(int64_t value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -1150,7 +1150,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(uint64_t value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -1398,7 +1398,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(float value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -1646,7 +1646,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(double value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -1894,7 +1894,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(BOOL value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
@@ -2166,7 +2166,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateRawValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block {
- [self enumerateRawValuesWithOptions:0 usingBlock:block];
+ [self enumerateRawValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts
@@ -2218,7 +2218,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) {
}
- (void)enumerateValuesWithBlock:(void (^)(int32_t value, NSUInteger idx, BOOL *stop))block {
- [self enumerateValuesWithOptions:0 usingBlock:block];
+ [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block];
}
- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts
diff --git a/objectivec/GPBBootstrap.h b/objectivec/GPBBootstrap.h
index 4db08e80..f14dd8aa 100644
--- a/objectivec/GPBBootstrap.h
+++ b/objectivec/GPBBootstrap.h
@@ -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.
-// The Objective C runtime has complete enough info that most protos don’t end
-// up using this, so leaving it on is no cost or very little cost. If you
-// happen to see it causing bloat, this is the way to disable it. If you do
-// need to disable it, try only disabling it for Release builds as having
-// full TextFormat can be useful for debugging.
+/**
+ * The Objective C runtime has complete enough info that most protos don’t end
+ * up using this, so leaving it on is no cost or very little cost. If you
+ * happen to see it causing bloat, this is the way to disable it. If you do
+ * need to disable it, try only disabling it for Release builds as having
+ * full TextFormat can be useful for debugging.
+ **/
#ifndef GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
#define GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS 0
#endif
@@ -42,6 +44,7 @@
#if !__has_feature(objc_fixed_enum)
#error All supported Xcode versions should support objc_fixed_enum.
#endif
+
// If the headers are imported into Objective-C++, we can run into an issue
// where the defintion of NS_ENUM (really CF_ENUM) changes based on the C++
// standard that is in effect. If it isn't C++11 or higher, the definition
@@ -53,19 +56,29 @@
#else
#define GPB_ENUM(X) NS_ENUM(int32_t, X)
#endif
-// GPB_ENUM_FWD_DECLARE is used for forward declaring enums, ex:
-// GPB_ENUM_FWD_DECLARE(Foo_Enum)
-// @property (nonatomic) Foo_Enum value;
+
+/**
+ * GPB_ENUM_FWD_DECLARE is used for forward declaring enums, for example:
+ *
+ * ```
+ * GPB_ENUM_FWD_DECLARE(Foo_Enum)
+ * @property (nonatomic) Foo_Enum value;
+ * ```
+ **/
#define GPB_ENUM_FWD_DECLARE(X) enum X : int32_t
-// Based upon CF_INLINE. Forces inlining in release.
+/**
+ * Based upon CF_INLINE. Forces inlining in non DEBUG builds.
+ **/
#if !defined(DEBUG)
#define GPB_INLINE static __inline__ __attribute__((always_inline))
#else
#define GPB_INLINE static __inline__
#endif
-// For use in public headers that might need to deal with ARC.
+/**
+ * For use in public headers that might need to deal with ARC.
+ **/
#ifndef GPB_UNSAFE_UNRETAINED
#if __has_feature(objc_arc)
#define GPB_UNSAFE_UNRETAINED __unsafe_unretained
@@ -76,10 +89,31 @@
// If property name starts with init we need to annotate it to get past ARC.
// http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227
+//
+// Meant to be used internally by generated code.
#define GPB_METHOD_FAMILY_NONE __attribute__((objc_method_family(none)))
-// The protoc-gen-objc version which works with the current version of the
-// generated Objective C sources. In general we don't want to change the
-// runtime interfaces (or this version) as it means everything has to be
-// regenerated.
+// ----------------------------------------------------------------------------
+// These version numbers are all internal to the ObjC Protobuf runtime; they
+// are used to ensure compatibility between the generated sources and the
+// headers being compiled against and/or the version of sources being run
+// against.
+//
+// They are all #defines so the values are captured into every .o file they
+// are used in and to allow comparisons in the preprocessor.
+
+// Current library runtime version.
+// - Gets bumped when the runtime makes changes to the interfaces between the
+// generated code and runtime (things added/removed, etc).
+#define GOOGLE_PROTOBUF_OBJC_VERSION 30002
+
+// Minimum runtime version supported for compiling/running against.
+// - Gets changed when support for the older generated code is dropped.
+#define GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION 30001
+
+
+// This is a legacy constant now frozen in time for old generated code. If
+// GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION ever gets moved above 30001 then
+// this should also change to break code compiled with an old runtime that
+// can't be supported any more.
#define GOOGLE_PROTOBUF_OBJC_GEN_VERSION 30001
diff --git a/objectivec/GPBCodedInputStream.h b/objectivec/GPBCodedInputStream.h
index df9d97ba..fbe5009c 100644
--- a/objectivec/GPBCodedInputStream.h
+++ b/objectivec/GPBCodedInputStream.h
@@ -37,125 +37,215 @@ NS_ASSUME_NONNULL_BEGIN
CF_EXTERN_C_BEGIN
-/// GPBCodedInputStream exception name. Exceptions raised from
-/// GPBCodedInputStream contain an underlying error in the userInfo dictionary
-/// under the GPBCodedInputStreamUnderlyingErrorKey key.
+/**
+ * @c GPBCodedInputStream exception name. Exceptions raised from
+ * @c GPBCodedInputStream contain an underlying error in the userInfo dictionary
+ * under the GPBCodedInputStreamUnderlyingErrorKey key.
+ **/
extern NSString *const GPBCodedInputStreamException;
-/// The key under which the underlying NSError from the exception is stored.
+/** The key under which the underlying NSError from the exception is stored. */
extern NSString *const GPBCodedInputStreamUnderlyingErrorKey;
-/// NSError domain used for GPBCodedInputStream errors.
+/** NSError domain used for @c GPBCodedInputStream errors. */
extern NSString *const GPBCodedInputStreamErrorDomain;
-/// Error code for NSError with GPBCodedInputStreamErrorDomain.
+/**
+ * Error code for NSError with @c GPBCodedInputStreamErrorDomain.
+ **/
typedef NS_ENUM(NSInteger, GPBCodedInputStreamErrorCode) {
- /// The size does not fit in the remaining bytes to be read.
+ /** The size does not fit in the remaining bytes to be read. */
GPBCodedInputStreamErrorInvalidSize = -100,
- /// Attempted to read beyond the subsection limit.
+ /** Attempted to read beyond the subsection limit. */
GPBCodedInputStreamErrorSubsectionLimitReached = -101,
- /// The requested subsection limit is invalid.
+ /** The requested subsection limit is invalid. */
GPBCodedInputStreamErrorInvalidSubsectionLimit = -102,
- /// Invalid tag read.
+ /** Invalid tag read. */
GPBCodedInputStreamErrorInvalidTag = -103,
- /// Invalid UTF-8 character in a string.
+ /** Invalid UTF-8 character in a string. */
GPBCodedInputStreamErrorInvalidUTF8 = -104,
- /// Invalid VarInt read.
+ /** Invalid VarInt read. */
GPBCodedInputStreamErrorInvalidVarInt = -105,
- /// The maximum recursion depth of messages was exceeded.
+ /** The maximum recursion depth of messages was exceeded. */
GPBCodedInputStreamErrorRecursionDepthExceeded = -106,
};
CF_EXTERN_C_END
-/// Reads and decodes protocol message fields.
-///
-/// The common uses of protocol buffers shouldn't need to use this class.
-/// @c GPBMessage's provide a @c +parseFromData:error: and @c
-/// +parseFromData:extensionRegistry:error: method that will decode a
-/// message for you.
-///
-/// @note Subclassing of GPBCodedInputStream is NOT supported.
+/**
+ * Reads and decodes protocol message fields.
+ *
+ * The common uses of protocol buffers shouldn't need to use this class.
+ * @c GPBMessage's provide a @c +parseFromData:error: and
+ * @c +parseFromData:extensionRegistry:error: method that will decode a
+ * message for you.
+ *
+ * @note Subclassing of @c GPBCodedInputStream is NOT supported.
+ **/
@interface GPBCodedInputStream : NSObject
-/// Creates a new stream wrapping some data.
+/**
+ * Creates a new stream wrapping some data.
+ *
+ * @param data The data to wrap inside the stream.
+ *
+ * @return A newly instanced GPBCodedInputStream.
+ **/
+ (instancetype)streamWithData:(NSData *)data;
-/// Initializes a stream wrapping some data.
+/**
+ * Initializes a stream wrapping some data.
+ *
+ * @param data The data to wrap inside the stream.
+ *
+ * @return A newly initialized GPBCodedInputStream.
+ **/
- (instancetype)initWithData:(NSData *)data;
-/// 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.
+/**
+ * Attempts 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.
+ *
+ * @return The field tag, or zero if EOF was reached.
+ **/
- (int32_t)readTag;
-/// Read and return a double.
+/**
+ * @return A double read from the stream.
+ **/
- (double)readDouble;
-/// Read and return a float.
+/**
+ * @return A float read from the stream.
+ **/
- (float)readFloat;
-/// Read and return a uint64.
+/**
+ * @return A uint64 read from the stream.
+ **/
- (uint64_t)readUInt64;
-/// Read and return a uint32.
+/**
+ * @return A uint32 read from the stream.
+ **/
- (uint32_t)readUInt32;
-/// Read and return an int64.
+/**
+ * @return An int64 read from the stream.
+ **/
- (int64_t)readInt64;
-/// Read and return an int32.
+/**
+ * @return An int32 read from the stream.
+ **/
- (int32_t)readInt32;
-/// Read and return a fixed64.
+/**
+ * @return A fixed64 read from the stream.
+ **/
- (uint64_t)readFixed64;
-/// Read and return a fixed32.
+/**
+ * @return A fixed32 read from the stream.
+ **/
- (uint32_t)readFixed32;
-/// Read and return an enum (int).
+/**
+ * @return An enum read from the stream.
+ **/
- (int32_t)readEnum;
-/// Read and return a sfixed32.
+/**
+ * @return A sfixed32 read from the stream.
+ **/
- (int32_t)readSFixed32;
-/// Read and return a sfixed64.
+/**
+ * @return A fixed64 read from the stream.
+ **/
- (int64_t)readSFixed64;
-/// Read and return a sint32.
+/**
+ * @return A sint32 read from the stream.
+ **/
- (int32_t)readSInt32;
-/// Read and return a sint64.
+/**
+ * @return A sint64 read from the stream.
+ **/
- (int64_t)readSInt64;
-/// Read and return a boolean.
+/**
+ * @return A boolean read from the stream.
+ **/
- (BOOL)readBool;
-/// Read and return a string.
+/**
+ * @return A string read from the stream.
+ **/
- (NSString *)readString;
-/// Read and return length delimited data.
+/**
+ * @return Data read from the stream.
+ **/
- (NSData *)readBytes;
-/// Read an embedded message field value from the stream.
-///
-/// @param message The message to set fields on as they are read.
-/// @param extensionRegistry An optional extension registry to use to lookup
-/// extensions for @c message.
+/**
+ * Read an embedded message field value from the stream.
+ *
+ * @param message The message to set fields on as they are read.
+ * @param extensionRegistry An optional extension registry to use to lookup
+ * extensions for message.
+ **/
- (void)readMessage:(GPBMessage *)message
extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry;
-/// Reads and discards a single field, given its tag value.
-///
-/// @param tag The tag number of the field to skip.
-///
-/// @return NO if the tag is an endgroup tag (in which case nothing is skipped),
-/// YES in all other cases.
+/**
+ * Reads and discards a single field, given its tag value.
+ *
+ * @param tag The tag number of the field to skip.
+ *
+ * @return NO if the tag is an endgroup tag (in which case nothing is skipped),
+ * YES in all other cases.
+ **/
- (BOOL)skipField:(int32_t)tag;
-/// Reads and discards an entire message. This will read either until EOF
-/// or until an endgroup tag, whichever comes first.
+/**
+ * Reads and discards an entire message. This will read either until EOF or
+ * until an endgroup tag, whichever comes first.
+ **/
- (void)skipMessage;
-/// Check to see if the logical end of the stream has been reached.
-///
-/// This can return NO when there is no more data, but the current parsing
-/// expected more data.
+/**
+ * Check to see if the logical end of the stream has been reached.
+ *
+ * @note This can return NO when there is no more data, but the current parsing
+ * expected more data.
+ *
+ * @return YES if the logical end of the stream has been reached, NO otherwise.
+ **/
- (BOOL)isAtEnd;
-/// The offset into the stream.
+/**
+ * @return The offset into the stream.
+ **/
- (size_t)position;
-/// Verifies that the last call to @c -readTag returned the given tag value.
-/// This is used to verify that a nested group ended with the correct end tag.
-/// Throws @c NSParseErrorException if value does not match the last tag.
-///
-/// @param expected The tag that was expected.
+/**
+ * Moves the limit to the given byte offset starting at the current location.
+ *
+ * @exception GPBCodedInputStreamException If the requested bytes exceeed the
+ * current limit.
+ *
+ * @param byteLimit The number of bytes to move the limit, offset to the current
+ * location.
+ *
+ * @return The limit offset before moving the new limit.
+ */
+- (size_t)pushLimit:(size_t)byteLimit;
+
+/**
+ * Moves the limit back to the offset as it was before calling pushLimit:.
+ *
+ * @param oldLimit The number of bytes to move the current limit. Usually this
+ * is the value returned by the pushLimit: method.
+ */
+- (void)popLimit:(size_t)oldLimit;
+
+/**
+ * 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.
+ *
+ * @exception NSParseErrorException If the value does not match the last tag.
+ *
+ * @param expected The tag that was expected.
+ **/
- (void)checkLastTagWas:(int32_t)expected;
@end
diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m
index 2b578dd5..e8c8989c 100644
--- a/objectivec/GPBCodedInputStream.m
+++ b/objectivec/GPBCodedInputStream.m
@@ -400,6 +400,14 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
return state_.bufferPos;
}
+- (size_t)pushLimit:(size_t)byteLimit {
+ return GPBCodedInputStreamPushLimit(&state_, byteLimit);
+}
+
+- (void)popLimit:(size_t)oldLimit {
+ GPBCodedInputStreamPopLimit(&state_, oldLimit);
+}
+
- (double)readDouble {
return GPBCodedInputStreamReadDouble(&state_);
}
diff --git a/objectivec/GPBCodedOutputStream.h b/objectivec/GPBCodedOutputStream.h
index 8272880d..d6fff3db 100644
--- a/objectivec/GPBCodedOutputStream.h
+++ b/objectivec/GPBCodedOutputStream.h
@@ -46,63 +46,122 @@
NS_ASSUME_NONNULL_BEGIN
-/// Writes out protocol message fields.
-///
-/// The common uses of protocol buffers shouldn't need to use this class.
-/// @c GPBMessage's provide a @c -data method that will serialize the message
-/// for you.
-///
-/// @note Subclassing of GPBCodedOutputStream is NOT supported.
+/**
+ * Writes out protocol message fields.
+ *
+ * The common uses of protocol buffers shouldn't need to use this class.
+ * GPBMessage's provide a -data method that will serialize the message for you.
+ *
+ * @note Subclassing of GPBCodedOutputStream is NOT supported.
+ **/
@interface GPBCodedOutputStream : NSObject
-/// Creates a stream to fill in the given data. Data must be sized to fit or
-/// an error will be raised when out of space.
+/**
+ * Creates a stream to fill in the given data. Data must be sized to fit or
+ * an error will be raised when out of space.
+ *
+ * @param data The data where the stream will be written to.
+ *
+ * @return A newly instanced GPBCodedOutputStream.
+ **/
+ (instancetype)streamWithData:(NSMutableData *)data;
-/// Creates a stream to write into the given @c NSOutputStream.
+/**
+ * Creates a stream to write into the given NSOutputStream.
+ *
+ * @param output The output stream where the stream will be written to.
+ *
+ * @return A newly instanced GPBCodedOutputStream.
+ **/
+ (instancetype)streamWithOutputStream:(NSOutputStream *)output;
-/// Initializes a stream to fill in the given data. Data must be sized to fit
-/// or an error will be raised when out of space.
+/**
+ * Initializes a stream to fill in the given data. Data must be sized to fit
+ * or an error will be raised when out of space.
+ *
+ * @param data The data where the stream will be written to.
+ *
+ * @return A newly initialized GPBCodedOutputStream.
+ **/
- (instancetype)initWithData:(NSMutableData *)data;
-/// Initializes a stream to write into the given @c NSOutputStream.
+/**
+ * Initializes a stream to write into the given @c NSOutputStream.
+ *
+ * @param output The output stream where the stream will be written to.
+ *
+ * @return A newly initialized GPBCodedOutputStream.
+ **/
- (instancetype)initWithOutputStream:(NSOutputStream *)output;
-/// Flush any buffered data out.
+/**
+ * Flush any buffered data out.
+ **/
- (void)flush;
-/// Write the raw byte out.
+/**
+ * Write the raw byte out.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeRawByte:(uint8_t)value;
-/// Write the tag for the given field number and wire format.
-///
-/// @param fieldNumber The field number.
-/// @param format The wire format the data for the field will be in.
+/**
+ * Write the tag for the given field number and wire format.
+ *
+ * @param fieldNumber The field number.
+ * @param format The wire format the data for the field will be in.
+ **/
- (void)writeTag:(uint32_t)fieldNumber format:(GPBWireFormat)format;
-/// Write a 32bit value out in little endian format.
+/**
+ * Write a 32bit value out in little endian format.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeRawLittleEndian32:(int32_t)value;
-/// Write a 64bit value out in little endian format.
+/**
+ * Write a 64bit value out in little endian format.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeRawLittleEndian64:(int64_t)value;
-/// Write a 32bit value out in varint format.
+/**
+ * Write a 32bit value out in varint format.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeRawVarint32:(int32_t)value;
-/// Write a 64bit value out in varint format.
+/**
+ * Write a 64bit value out in varint format.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeRawVarint64:(int64_t)value;
-/// Write a size_t out as a 32bit varint value.
-///
-/// @note This will truncate 64 bit values to 32.
+/**
+ * Write a size_t out as a 32bit varint value.
+ *
+ * @note This will truncate 64 bit values to 32.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeRawVarintSizeTAs32:(size_t)value;
-/// Writes the contents of an @c NSData out.
+/**
+ * Writes the contents of an NSData out.
+ *
+ * @param data The data to write out.
+ **/
- (void)writeRawData:(NSData *)data;
-/// Writes out the given data.
-///
-/// @param data The data blob to write out.
-/// @param offset The offset into the blob to start writing out.
-/// @param length The number of bytes from the blob to write out.
+/**
+ * Writes out the given data.
+ *
+ * @param data The data blob to write out.
+ * @param offset The offset into the blob to start writing out.
+ * @param length The number of bytes from the blob to write out.
+ **/
- (void)writeRawPtr:(const void *)data
offset:(size_t)offset
length:(size_t)length;
@@ -110,179 +169,471 @@ NS_ASSUME_NONNULL_BEGIN
//%PDDM-EXPAND _WRITE_DECLS()
// This block of code is generated, do not edit it directly.
-/// Write a double for the given field number.
+/**
+ * Write a double for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeDouble:(int32_t)fieldNumber value:(double)value;
-/// Write a packed array of double for the given field number.
+/**
+ * Write a packed array of double for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeDoubleArray:(int32_t)fieldNumber
values:(GPBDoubleArray *)values
tag:(uint32_t)tag;
-/// Write a double without any tag.
+/**
+ * Write a double without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeDoubleNoTag:(double)value;
-/// Write a float for the given field number.
+/**
+ * Write a float for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeFloat:(int32_t)fieldNumber value:(float)value;
-/// Write a packed array of float for the given field number.
+/**
+ * Write a packed array of float for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeFloatArray:(int32_t)fieldNumber
values:(GPBFloatArray *)values
tag:(uint32_t)tag;
-/// Write a float without any tag.
+/**
+ * Write a float without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeFloatNoTag:(float)value;
-/// Write a uint64_t for the given field number.
+/**
+ * Write a uint64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeUInt64:(int32_t)fieldNumber value:(uint64_t)value;
-/// Write a packed array of uint64_t for the given field number.
+/**
+ * Write a packed array of uint64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeUInt64Array:(int32_t)fieldNumber
values:(GPBUInt64Array *)values
tag:(uint32_t)tag;
-/// Write a uint64_t without any tag.
+/**
+ * Write a uint64_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeUInt64NoTag:(uint64_t)value;
-/// Write a int64_t for the given field number.
+/**
+ * Write a int64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeInt64:(int32_t)fieldNumber value:(int64_t)value;
-/// Write a packed array of int64_t for the given field number.
+/**
+ * Write a packed array of int64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeInt64Array:(int32_t)fieldNumber
values:(GPBInt64Array *)values
tag:(uint32_t)tag;
-/// Write a int64_t without any tag.
+/**
+ * Write a int64_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeInt64NoTag:(int64_t)value;
-/// Write a int32_t for the given field number.
+/**
+ * Write a int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeInt32:(int32_t)fieldNumber value:(int32_t)value;
-/// Write a packed array of int32_t for the given field number.
+/**
+ * Write a packed array of int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeInt32Array:(int32_t)fieldNumber
values:(GPBInt32Array *)values
tag:(uint32_t)tag;
-/// Write a int32_t without any tag.
+/**
+ * Write a int32_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeInt32NoTag:(int32_t)value;
-/// Write a uint32_t for the given field number.
+/**
+ * Write a uint32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeUInt32:(int32_t)fieldNumber value:(uint32_t)value;
-/// Write a packed array of uint32_t for the given field number.
+/**
+ * Write a packed array of uint32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeUInt32Array:(int32_t)fieldNumber
values:(GPBUInt32Array *)values
tag:(uint32_t)tag;
-/// Write a uint32_t without any tag.
+/**
+ * Write a uint32_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeUInt32NoTag:(uint32_t)value;
-/// Write a uint64_t for the given field number.
+/**
+ * Write a uint64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeFixed64:(int32_t)fieldNumber value:(uint64_t)value;
-/// Write a packed array of uint64_t for the given field number.
+/**
+ * Write a packed array of uint64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeFixed64Array:(int32_t)fieldNumber
values:(GPBUInt64Array *)values
tag:(uint32_t)tag;
-/// Write a uint64_t without any tag.
+/**
+ * Write a uint64_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeFixed64NoTag:(uint64_t)value;
-/// Write a uint32_t for the given field number.
+/**
+ * Write a uint32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeFixed32:(int32_t)fieldNumber value:(uint32_t)value;
-/// Write a packed array of uint32_t for the given field number.
+/**
+ * Write a packed array of uint32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeFixed32Array:(int32_t)fieldNumber
values:(GPBUInt32Array *)values
tag:(uint32_t)tag;
-/// Write a uint32_t without any tag.
+/**
+ * Write a uint32_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeFixed32NoTag:(uint32_t)value;
-/// Write a int32_t for the given field number.
+/**
+ * Write a int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeSInt32:(int32_t)fieldNumber value:(int32_t)value;
-/// Write a packed array of int32_t for the given field number.
+/**
+ * Write a packed array of int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeSInt32Array:(int32_t)fieldNumber
values:(GPBInt32Array *)values
tag:(uint32_t)tag;
-/// Write a int32_t without any tag.
+/**
+ * Write a int32_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeSInt32NoTag:(int32_t)value;
-/// Write a int64_t for the given field number.
+/**
+ * Write a int64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeSInt64:(int32_t)fieldNumber value:(int64_t)value;
-/// Write a packed array of int64_t for the given field number.
+/**
+ * Write a packed array of int64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeSInt64Array:(int32_t)fieldNumber
values:(GPBInt64Array *)values
tag:(uint32_t)tag;
-/// Write a int64_t without any tag.
+/**
+ * Write a int64_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeSInt64NoTag:(int64_t)value;
-/// Write a int64_t for the given field number.
+/**
+ * Write a int64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeSFixed64:(int32_t)fieldNumber value:(int64_t)value;
-/// Write a packed array of int64_t for the given field number.
+/**
+ * Write a packed array of int64_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeSFixed64Array:(int32_t)fieldNumber
values:(GPBInt64Array *)values
tag:(uint32_t)tag;
-/// Write a int64_t without any tag.
+/**
+ * Write a int64_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeSFixed64NoTag:(int64_t)value;
-/// Write a int32_t for the given field number.
+/**
+ * Write a int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeSFixed32:(int32_t)fieldNumber value:(int32_t)value;
-/// Write a packed array of int32_t for the given field number.
+/**
+ * Write a packed array of int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeSFixed32Array:(int32_t)fieldNumber
values:(GPBInt32Array *)values
tag:(uint32_t)tag;
-/// Write a int32_t without any tag.
+/**
+ * Write a int32_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeSFixed32NoTag:(int32_t)value;
-/// Write a BOOL for the given field number.
+/**
+ * Write a BOOL for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeBool:(int32_t)fieldNumber value:(BOOL)value;
-/// Write a packed array of BOOL for the given field number.
+/**
+ * Write a packed array of BOOL for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeBoolArray:(int32_t)fieldNumber
values:(GPBBoolArray *)values
tag:(uint32_t)tag;
-/// Write a BOOL without any tag.
+/**
+ * Write a BOOL without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeBoolNoTag:(BOOL)value;
-/// Write a int32_t for the given field number.
+/**
+ * Write a int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeEnum:(int32_t)fieldNumber value:(int32_t)value;
-/// Write a packed array of int32_t for the given field number.
+/**
+ * Write a packed array of int32_t for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ * @param tag The tag assigned to the values.
+ **/
- (void)writeEnumArray:(int32_t)fieldNumber
values:(GPBEnumArray *)values
tag:(uint32_t)tag;
-/// Write a int32_t without any tag.
+/**
+ * Write a int32_t without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeEnumNoTag:(int32_t)value;
-/// Write a NSString for the given field number.
+/**
+ * Write a NSString for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeString:(int32_t)fieldNumber value:(NSString *)value;
-/// Write an array of NSString for the given field number.
+/**
+ * Write an array of NSString for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ **/
- (void)writeStringArray:(int32_t)fieldNumber values:(NSArray<NSString*> *)values;
-/// Write a NSString without any tag.
+/**
+ * Write a NSString without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeStringNoTag:(NSString *)value;
-/// Write a GPBMessage for the given field number.
+/**
+ * Write a GPBMessage for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeMessage:(int32_t)fieldNumber value:(GPBMessage *)value;
-/// Write an array of GPBMessage for the given field number.
+/**
+ * Write an array of GPBMessage for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ **/
- (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray<GPBMessage*> *)values;
-/// Write a GPBMessage without any tag.
+/**
+ * Write a GPBMessage without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeMessageNoTag:(GPBMessage *)value;
-/// Write a NSData for the given field number.
+/**
+ * Write a NSData for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeBytes:(int32_t)fieldNumber value:(NSData *)value;
-/// Write an array of NSData for the given field number.
+/**
+ * Write an array of NSData for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ **/
- (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray<NSData*> *)values;
-/// Write a NSData without any tag.
+/**
+ * Write a NSData without any tag.
+ *
+ * @param value The value to write out.
+ **/
- (void)writeBytesNoTag:(NSData *)value;
-/// Write a GPBMessage for the given field number.
+/**
+ * Write a GPBMessage for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeGroup:(int32_t)fieldNumber
value:(GPBMessage *)value;
-/// Write an array of GPBMessage for the given field number.
+/**
+ * Write an array of GPBMessage for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ **/
- (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray<GPBMessage*> *)values;
-/// Write a GPBMessage without any tag (but does write the endGroup tag).
+/**
+ * Write a GPBMessage without any tag (but does write the endGroup tag).
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeGroupNoTag:(int32_t)fieldNumber
value:(GPBMessage *)value;
-/// Write a GPBUnknownFieldSet for the given field number.
+/**
+ * Write a GPBUnknownFieldSet for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeUnknownGroup:(int32_t)fieldNumber
value:(GPBUnknownFieldSet *)value;
-/// Write an array of GPBUnknownFieldSet for the given field number.
+/**
+ * Write an array of GPBUnknownFieldSet for the given field number.
+ *
+ * @param fieldNumber The field number assigned to the values.
+ * @param values The values to write out.
+ **/
- (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray<GPBUnknownFieldSet*> *)values;
-/// Write a GPBUnknownFieldSet without any tag (but does write the endGroup tag).
+/**
+ * Write a GPBUnknownFieldSet without any tag (but does write the endGroup tag).
+ *
+ * @param fieldNumber The field number assigned to the value.
+ * @param value The value to write out.
+ **/
- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber
value:(GPBUnknownFieldSet *)value;
//%PDDM-EXPAND-END _WRITE_DECLS()
-/// Write a MessageSet extension field to the stream. For historical reasons,
-/// the wire format differs from normal fields.
+/**
+Write a MessageSet extension field to the stream. For historical reasons,
+the wire format differs from normal fields.
+
+@param fieldNumber The extension field number to write out.
+@param value The message from where to get the extension.
+*/
- (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value;
-/// Write an unparsed MessageSet extension field to the stream. For
-/// historical reasons, the wire format differs from normal fields.
+/**
+Write an unparsed MessageSet extension field to the stream. For historical
+reasons, the wire format differs from normal fields.
+
+@param fieldNumber The extension field number to write out.
+@param value The raw message from where to get the extension.
+*/
- (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value;
@end
@@ -291,32 +642,76 @@ NS_ASSUME_NONNULL_END
// Write methods for types that can be in packed arrays.
//%PDDM-DEFINE _WRITE_PACKABLE_DECLS(NAME, ARRAY_TYPE, TYPE)
-//%/// Write a TYPE for the given field number.
+//%/**
+//% * Write a TYPE for the given field number.
+//% *
+//% * @param fieldNumber The field number assigned to the value.
+//% * @param value The value to write out.
+//% **/
//%- (void)write##NAME:(int32_t)fieldNumber value:(TYPE)value;
-//%/// Write a packed array of TYPE for the given field number.
+//%/**
+//% * Write a packed array of TYPE for the given field number.
+//% *
+//% * @param fieldNumber The field number assigned to the values.
+//% * @param values The values to write out.
+//% * @param tag The tag assigned to the values.
+//% **/
//%- (void)write##NAME##Array:(int32_t)fieldNumber
//% NAME$S values:(GPB##ARRAY_TYPE##Array *)values
//% NAME$S tag:(uint32_t)tag;
-//%/// Write a TYPE without any tag.
+//%/**
+//% * Write a TYPE without any tag.
+//% *
+//% * @param value The value to write out.
+//% **/
//%- (void)write##NAME##NoTag:(TYPE)value;
//%
// Write methods for types that aren't in packed arrays.
//%PDDM-DEFINE _WRITE_UNPACKABLE_DECLS(NAME, TYPE)
-//%/// Write a TYPE for the given field number.
+//%/**
+//% * Write a TYPE for the given field number.
+//% *
+//% * @param fieldNumber The field number assigned to the value.
+//% * @param value The value to write out.
+//% **/
//%- (void)write##NAME:(int32_t)fieldNumber value:(TYPE *)value;
-//%/// Write an array of TYPE for the given field number.
+//%/**
+//% * Write an array of TYPE for the given field number.
+//% *
+//% * @param fieldNumber The field number assigned to the values.
+//% * @param values The values to write out.
+//% **/
//%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray<##TYPE##*> *)values;
-//%/// Write a TYPE without any tag.
+//%/**
+//% * Write a TYPE without any tag.
+//% *
+//% * @param value The value to write out.
+//% **/
//%- (void)write##NAME##NoTag:(TYPE *)value;
//%
// Special write methods for Groups.
//%PDDM-DEFINE _WRITE_GROUP_DECLS(NAME, TYPE)
-//%/// Write a TYPE for the given field number.
+//%/**
+//% * Write a TYPE for the given field number.
+//% *
+//% * @param fieldNumber The field number assigned to the value.
+//% * @param value The value to write out.
+//% **/
//%- (void)write##NAME:(int32_t)fieldNumber
//% NAME$S value:(TYPE *)value;
-//%/// Write an array of TYPE for the given field number.
+//%/**
+//% * Write an array of TYPE for the given field number.
+//% *
+//% * @param fieldNumber The field number assigned to the values.
+//% * @param values The values to write out.
+//% **/
//%- (void)write##NAME##Array:(int32_t)fieldNumber values:(NSArray<##TYPE##*> *)values;
-//%/// Write a TYPE without any tag (but does write the endGroup tag).
+//%/**
+//% * Write a TYPE without any tag (but does write the endGroup tag).
+//% *
+//% * @param fieldNumber The field number assigned to the value.
+//% * @param value The value to write out.
+//% **/
//%- (void)write##NAME##NoTag:(int32_t)fieldNumber
//% NAME$S value:(TYPE *)value;
//%
diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m
index 63ba8068..7c3ab447 100644
--- a/objectivec/GPBCodedOutputStream.m
+++ b/objectivec/GPBCodedOutputStream.m
@@ -144,22 +144,6 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
GPBWriteRawByte(state, (int32_t)(value >> 56) & 0xFF);
}
-#if defined(DEBUG) && DEBUG && !defined(NS_BLOCK_ASSERTIONS)
-+ (void)load {
- // This test exists to verify that CFStrings with embedded NULLs will work
- // for us. If this Assert fails, all code below that depends on
- // CFStringGetCStringPtr will NOT work properly on strings that contain
- // embedded NULLs, and we do get that in some protobufs.
- // Note that this will not be compiled in release.
- // We didn't feel that just keeping it in a unit test was sufficient because
- // the Protobuf unit tests are only run when somebody is actually working
- // on protobufs.
- CFStringRef zeroTest = CFSTR("Test\0String");
- const char *cString = CFStringGetCStringPtr(zeroTest, kCFStringEncodingUTF8);
- NSAssert(cString == NULL, @"Serious Error");
-}
-#endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS)
-
- (void)dealloc {
[self flush];
[state_.output close];
@@ -282,19 +266,15 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
}
- (void)writeStringNoTag:(const NSString *)value {
- // If you are concerned about embedded NULLs see the test in
- // +load above.
- const char *quickString =
- CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8);
- size_t length = (quickString != NULL)
- ? strlen(quickString)
- : [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
+ size_t length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
GPBWriteRawVarint32(&state_, (int32_t)length);
-
if (length == 0) {
return;
}
+ const char *quickString =
+ CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8);
+
// Fast path: Most strings are short, if the buffer already has space,
// add to it directly.
NSUInteger bufferBytesLeft = state_.size - state_.position;
@@ -310,7 +290,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state,
maxLength:bufferBytesLeft
usedLength:&usedBufferLength
encoding:NSUTF8StringEncoding
- options:0
+ options:(NSStringEncodingConversionOptions)0
range:NSMakeRange(0, [value length])
remainingRange:NULL];
}
@@ -1038,14 +1018,7 @@ size_t GPBComputeBoolSizeNoTag(BOOL value) {
}
size_t GPBComputeStringSizeNoTag(NSString *value) {
- // If you are concerned about embedded NULLs see the test in
- // +load above.
- const char *quickString =
- CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8);
- NSUInteger length =
- (quickString != NULL)
- ? strlen(quickString)
- : [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
+ NSUInteger length = [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
return GPBComputeRawVarint32SizeForInteger(length) + length;
}
diff --git a/objectivec/GPBDescriptor.h b/objectivec/GPBDescriptor.h
index fe4ff390..651f4de0 100644
--- a/objectivec/GPBDescriptor.h
+++ b/objectivec/GPBDescriptor.h
@@ -39,104 +39,250 @@
NS_ASSUME_NONNULL_BEGIN
+/** Syntax used in the proto file. */
typedef NS_ENUM(uint8_t, GPBFileSyntax) {
+ /** Unknown syntax. */
GPBFileSyntaxUnknown = 0,
+ /** Proto2 syntax. */
GPBFileSyntaxProto2 = 2,
+ /** Proto3 syntax. */
GPBFileSyntaxProto3 = 3,
};
+/** Type of proto field. */
typedef NS_ENUM(uint8_t, GPBFieldType) {
- GPBFieldTypeSingle, // optional/required
- GPBFieldTypeRepeated, // repeated
- GPBFieldTypeMap, // map<K,V>
+ /** Optional/required field. Only valid for proto2 fields. */
+ GPBFieldTypeSingle,
+ /** Repeated field. */
+ GPBFieldTypeRepeated,
+ /** Map field. */
+ GPBFieldTypeMap,
};
+/**
+ * Describes a proto message.
+ **/
@interface GPBDescriptor : NSObject<NSCopying>
+/** Name of the message. */
@property(nonatomic, readonly, copy) NSString *name;
+/** Fields declared in the message. */
@property(nonatomic, readonly, strong, nullable) NSArray<GPBFieldDescriptor*> *fields;
+/** Oneofs declared in the message. */
@property(nonatomic, readonly, strong, nullable) NSArray<GPBOneofDescriptor*> *oneofs;
+/** Extension range declared for the message. */
@property(nonatomic, readonly, nullable) const GPBExtensionRange *extensionRanges;
+/** Number of extension ranges declared for the message. */
@property(nonatomic, readonly) uint32_t extensionRangesCount;
+/** Descriptor for the file where the message was defined. */
@property(nonatomic, readonly, assign) GPBFileDescriptor *file;
+/** Whether the message is in wire format or not. */
@property(nonatomic, readonly, getter=isWireFormat) BOOL wireFormat;
+/** The class of this message. */
@property(nonatomic, readonly) Class messageClass;
+/** Containing message descriptor if this message is nested, or nil otherwise. */
+@property(readonly, nullable) GPBDescriptor *containingType;
+/**
+ * Fully qualified name for this message (package.message). Can be nil if the
+ * value is unable to be computed.
+ */
+@property(readonly, nullable) NSString *fullName;
+/**
+ * Gets the field for the given number.
+ *
+ * @param fieldNumber The number for the field to get.
+ *
+ * @return The field descriptor for the given number, or nil if not found.
+ **/
- (nullable GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber;
+
+/**
+ * Gets the field for the given name.
+ *
+ * @param name The name for the field to get.
+ *
+ * @return The field descriptor for the given name, or nil if not found.
+ **/
- (nullable GPBFieldDescriptor *)fieldWithName:(NSString *)name;
+
+/**
+ * Gets the oneof for the given name.
+ *
+ * @param name The name for the oneof to get.
+ *
+ * @return The oneof descriptor for the given name, or nil if not found.
+ **/
- (nullable GPBOneofDescriptor *)oneofWithName:(NSString *)name;
@end
+/**
+ * Describes a proto file.
+ **/
@interface GPBFileDescriptor : NSObject
+/** The package declared in the proto file. */
@property(nonatomic, readonly, copy) NSString *package;
+/** The objc prefix declared in the proto file. */
+@property(nonatomic, readonly, copy, nullable) NSString *objcPrefix;
+/** The syntax of the proto file. */
@property(nonatomic, readonly) GPBFileSyntax syntax;
@end
+/**
+ * Describes a oneof field.
+ **/
@interface GPBOneofDescriptor : NSObject
+/** Name of the oneof field. */
@property(nonatomic, readonly) NSString *name;
+/** Fields declared in the oneof. */
@property(nonatomic, readonly) NSArray<GPBFieldDescriptor*> *fields;
+/**
+ * Gets the field for the given number.
+ *
+ * @param fieldNumber The number for the field to get.
+ *
+ * @return The field descriptor for the given number, or nil if not found.
+ **/
- (nullable GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber;
+
+/**
+ * Gets the field for the given name.
+ *
+ * @param name The name for the field to get.
+ *
+ * @return The field descriptor for the given name, or nil if not found.
+ **/
- (nullable GPBFieldDescriptor *)fieldWithName:(NSString *)name;
+
@end
+/**
+ * Describes a proto field.
+ **/
@interface GPBFieldDescriptor : NSObject
+/** Name of the field. */
@property(nonatomic, readonly, copy) NSString *name;
+/** Number associated with the field. */
@property(nonatomic, readonly) uint32_t number;
+/** Data type contained in the field. */
@property(nonatomic, readonly) GPBDataType dataType;
+/** Whether it has a default value or not. */
@property(nonatomic, readonly) BOOL hasDefaultValue;
+/** Default value for the field. */
@property(nonatomic, readonly) GPBGenericValue defaultValue;
+/** Whether this field is required. Only valid for proto2 fields. */
@property(nonatomic, readonly, getter=isRequired) BOOL required;
+/** Whether this field is optional. */
@property(nonatomic, readonly, getter=isOptional) BOOL optional;
+/** Type of field (single, repeated, map). */
@property(nonatomic, readonly) GPBFieldType fieldType;
-// If it is a map, the value type is in -type.
+/** Type of the key if the field is a map. The value's type is -fieldType. */
@property(nonatomic, readonly) GPBDataType mapKeyDataType;
+/** Whether the field is packable. */
@property(nonatomic, readonly, getter=isPackable) BOOL packable;
+/** The containing oneof if this field is part of one, nil otherwise. */
@property(nonatomic, readonly, assign, nullable) GPBOneofDescriptor *containingOneof;
-// Message properties
+/** Class of the message if the field is of message type. */
@property(nonatomic, readonly, assign, nullable) Class msgClass;
-// Enum properties
+/** Descriptor for the enum if this field is an enum. */
@property(nonatomic, readonly, strong, nullable) GPBEnumDescriptor *enumDescriptor;
+/**
+ * Checks whether the given enum raw value is a valid enum value.
+ *
+ * @param value The raw enum value to check.
+ *
+ * @return YES if value is a valid enum raw value.
+ **/
- (BOOL)isValidEnumValue:(int32_t)value;
-// For now, this will return nil if it doesn't know the name to use for
-// TextFormat.
+/** @return Name for the text format, or nil if not known. */
- (nullable NSString *)textFormatName;
@end
+/**
+ * Describes a proto enum.
+ **/
@interface GPBEnumDescriptor : NSObject
+/** Name of the enum. */
@property(nonatomic, readonly, copy) NSString *name;
+/** Function that validates that raw values are valid enum values. */
@property(nonatomic, readonly) GPBEnumValidationFunc enumVerifier;
+/**
+ * Returns the enum value name for the given raw enum.
+ *
+ * @param number The raw enum value.
+ *
+ * @return The name of the enum value passed, or nil if not valid.
+ **/
- (nullable NSString *)enumNameForValue:(int32_t)number;
+
+/**
+ * Gets the enum raw value for the given enum name.
+ *
+ * @param outValue A pointer where the value will be set.
+ * @param name The enum name for which to get the raw value.
+ *
+ * @return YES if a value was copied into the pointer, NO otherwise.
+ **/
- (BOOL)getValue:(nullable int32_t *)outValue forEnumName:(NSString *)name;
+/**
+ * Returns the text format for the given raw enum value.
+ *
+ * @param number The raw enum value.
+ *
+ * @return The text format name for the raw enum value, or nil if not valid.
+ **/
- (nullable NSString *)textFormatNameForValue:(int32_t)number;
+
+/**
+ * Gets the enum raw value for the given text format name.
+ *
+ * @param outValue A pointer where the value will be set.
+ * @param textFormatName The text format name for which to get the raw value.
+ *
+ * @return YES if a value was copied into the pointer, NO otherwise.
+ **/
- (BOOL)getValue:(nullable int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName;
@end
+/**
+ * Describes a proto extension.
+ **/
@interface GPBExtensionDescriptor : NSObject<NSCopying>
+/** Field number under which the extension is stored. */
@property(nonatomic, readonly) uint32_t fieldNumber;
+/** The containing message class, i.e. the class extended by this extension. */
@property(nonatomic, readonly) Class containingMessageClass;
+/** Data type contained in the extension. */
@property(nonatomic, readonly) GPBDataType dataType;
+/** Whether the extension is repeated. */
@property(nonatomic, readonly, getter=isRepeated) BOOL repeated;
+/** Whether the extension is packable. */
@property(nonatomic, readonly, getter=isPackable) BOOL packable;
+/** The class of the message if the extension is of message type. */
@property(nonatomic, readonly, assign) Class msgClass;
+/** The singleton name for the extension. */
@property(nonatomic, readonly) NSString *singletonName;
+/** The enum descriptor if the extension is of enum type. */
@property(nonatomic, readonly, strong, nullable) GPBEnumDescriptor *enumDescriptor;
+/** The default value for the extension. */
@property(nonatomic, readonly, nullable) id defaultValue;
+
@end
NS_ASSUME_NONNULL_END
diff --git a/objectivec/GPBDescriptor.m b/objectivec/GPBDescriptor.m
index dccb9bc8..0753a948 100644
--- a/objectivec/GPBDescriptor.m
+++ b/objectivec/GPBDescriptor.m
@@ -42,8 +42,10 @@
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdirect-ivar-access"
-// The address of this variable is used as a key for obj_getAssociatedObject.
+// The addresses of these variables are used as keys for objc_getAssociatedObject.
static const char kTextFormatExtraValueKey = 0;
+static const char kParentClassNameValueKey = 0;
+static const char kClassNameSuffixKey = 0;
// Utility function to generate selectors on the fly.
static SEL SelFromStrings(const char *prefix, const char *middle,
@@ -215,10 +217,102 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
extensionRangesCount_ = count;
}
+- (void)setupContainingMessageClassName:(const char *)msgClassName {
+ // Note: Only fetch the class here, can't send messages to it because
+ // that could cause cycles back to this class within +initialize if
+ // two messages have each other in fields (i.e. - they build a graph).
+ NSAssert(objc_getClass(msgClassName), @"Class %s not defined", msgClassName);
+ NSValue *parentNameValue = [NSValue valueWithPointer:msgClassName];
+ objc_setAssociatedObject(self, &kParentClassNameValueKey,
+ parentNameValue,
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+
+- (void)setupMessageClassNameSuffix:(NSString *)suffix {
+ if (suffix.length) {
+ objc_setAssociatedObject(self, &kClassNameSuffixKey,
+ suffix,
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+}
+
- (NSString *)name {
return NSStringFromClass(messageClass_);
}
+- (GPBDescriptor *)containingType {
+ NSValue *parentNameValue =
+ objc_getAssociatedObject(self, &kParentClassNameValueKey);
+ if (!parentNameValue) {
+ return nil;
+ }
+ const char *parentName = [parentNameValue pointerValue];
+ Class parentClass = objc_getClass(parentName);
+ NSAssert(parentClass, @"Class %s not defined", parentName);
+ return [parentClass descriptor];
+}
+
+- (NSString *)fullName {
+ NSString *className = NSStringFromClass(self.messageClass);
+ GPBFileDescriptor *file = self.file;
+ NSString *objcPrefix = file.objcPrefix;
+ if (objcPrefix && ![className hasPrefix:objcPrefix]) {
+ NSAssert(0,
+ @"Class didn't have correct prefix? (%@ - %@)",
+ className, objcPrefix);
+ return nil;
+ }
+ GPBDescriptor *parent = self.containingType;
+
+ NSString *name = nil;
+ if (parent) {
+ NSString *parentClassName = NSStringFromClass(parent.messageClass);
+ // The generator will add _Class to avoid reserved words, drop it.
+ NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey);
+ if (suffix) {
+ if (![parentClassName hasSuffix:suffix]) {
+ NSAssert(0,
+ @"ParentMessage class didn't have correct suffix? (%@ - %@)",
+ className, suffix);
+ return nil;
+ }
+ parentClassName =
+ [parentClassName substringToIndex:(parentClassName.length - suffix.length)];
+ }
+ NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"];
+ if (![className hasPrefix:parentPrefix]) {
+ NSAssert(0,
+ @"Class didn't have the correct parent name prefix? (%@ - %@)",
+ parentPrefix, className);
+ return nil;
+ }
+ name = [className substringFromIndex:parentPrefix.length];
+ } else {
+ name = [className substringFromIndex:objcPrefix.length];
+ }
+
+ // The generator will add _Class to avoid reserved words, drop it.
+ NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey);
+ if (suffix) {
+ if (![name hasSuffix:suffix]) {
+ NSAssert(0,
+ @"Message class didn't have correct suffix? (%@ - %@)",
+ name, suffix);
+ return nil;
+ }
+ name = [name substringToIndex:(name.length - suffix.length)];
+ }
+
+ NSString *prefix = (parent != nil ? parent.fullName : file.package);
+ NSString *result;
+ if (prefix.length > 0) {
+ result = [NSString stringWithFormat:@"%@.%@", prefix, name];
+ } else {
+ result = name;
+ }
+ return result;
+}
+
- (id)copyWithZone:(NSZone *)zone {
#pragma unused(zone)
return [self retain];
@@ -255,13 +349,27 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
@implementation GPBFileDescriptor {
NSString *package_;
+ NSString *objcPrefix_;
GPBFileSyntax syntax_;
}
@synthesize package = package_;
+@synthesize objcPrefix = objcPrefix_;
@synthesize syntax = syntax_;
- (instancetype)initWithPackage:(NSString *)package
+ objcPrefix:(NSString *)objcPrefix
+ syntax:(GPBFileSyntax)syntax {
+ self = [super init];
+ if (self) {
+ package_ = [package copy];
+ objcPrefix_ = [objcPrefix copy];
+ syntax_ = syntax;
+ }
+ return self;
+}
+
+- (instancetype)initWithPackage:(NSString *)package
syntax:(GPBFileSyntax)syntax {
self = [super init];
if (self) {
@@ -273,6 +381,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex,
- (void)dealloc {
[package_ release];
+ [objcPrefix_ release];
[super dealloc];
}
@@ -416,6 +525,9 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) {
// Extra type specific data.
if (isMessage) {
const char *className = coreDesc->dataTypeSpecific.className;
+ // Note: Only fetch the class here, can't send messages to it because
+ // that could cause cycles back to this class within +initialize if
+ // two messages have each other in fields (i.e. - they build a graph).
msgClass_ = objc_getClass(className);
NSAssert(msgClass_, @"Class %s not defined", className);
} else if (dataType == GPBDataTypeEnum) {
diff --git a/objectivec/GPBDescriptor_PackagePrivate.h b/objectivec/GPBDescriptor_PackagePrivate.h
index c20ff6b0..9173e7a2 100644
--- a/objectivec/GPBDescriptor_PackagePrivate.h
+++ b/objectivec/GPBDescriptor_PackagePrivate.h
@@ -37,6 +37,7 @@
// Describes attributes of the field.
typedef NS_OPTIONS(uint16_t, GPBFieldFlags) {
+ GPBFieldNone = 0,
// These map to standard protobuf concepts.
GPBFieldRequired = 1 << 0,
GPBFieldRepeated = 1 << 1,
@@ -111,6 +112,7 @@ typedef struct GPBMessageFieldDescriptionWithDefault {
// Describes attributes of the extension.
typedef NS_OPTIONS(uint8_t, GPBExtensionOptions) {
+ GPBExtensionNone = 0,
// These map to standard protobuf concepts.
GPBExtensionRepeated = 1 << 0,
GPBExtensionPacked = 1 << 1,
@@ -130,6 +132,7 @@ typedef struct GPBExtensionDescription {
} GPBExtensionDescription;
typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) {
+ GPBDescriptorInitializationFlag_None = 0,
GPBDescriptorInitializationFlag_FieldsWithDefault = 1 << 0,
GPBDescriptorInitializationFlag_WireFormat = 1 << 1,
};
@@ -165,11 +168,16 @@ typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) {
firstHasIndex:(int32_t)firstHasIndex;
- (void)setupExtraTextInfo:(const char *)extraTextFormatInfo;
- (void)setupExtensionRanges:(const GPBExtensionRange *)ranges count:(int32_t)count;
+- (void)setupContainingMessageClassName:(const char *)msgClassName;
+- (void)setupMessageClassNameSuffix:(NSString *)suffix;
@end
@interface GPBFileDescriptor ()
- (instancetype)initWithPackage:(NSString *)package
+ objcPrefix:(NSString *)objcPrefix
+ syntax:(GPBFileSyntax)syntax;
+- (instancetype)initWithPackage:(NSString *)package
syntax:(GPBFileSyntax)syntax;
@end
diff --git a/objectivec/GPBDictionary.h b/objectivec/GPBDictionary.h
index f7959960..4b2b9ff3 100644
--- a/objectivec/GPBDictionary.h
+++ b/objectivec/GPBDictionary.h
@@ -32,11 +32,6 @@
#import "GPBRuntimeTypes.h"
-// These classes are used for map fields of basic data types. They are used because
-// they perform better than boxing into NSNumbers in NSDictionaries.
-
-// Note: These are not meant to be subclassed.
-
// Note on naming: for the classes holding numeric values, a more natural
// naming of the method might be things like "-valueForKey:",
// "-setValue:forKey:"; etc. But those selectors are also defined by Key Value
@@ -53,289 +48,1134 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - UInt32 -> UInt32
+/**
+ * Class used for map fields of <uint32_t, uint32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32UInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt32:(uint32_t)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt32s:(const uint32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32UInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(uint32_t key, uint32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32UInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt32:(uint32_t)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt32ForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Int32
+/**
+ * Class used for map fields of <uint32_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32Int32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt32:(int32_t)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt32s:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32Int32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt32:(nullable int32_t *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(uint32_t key, int32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32Int32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt32:(int32_t)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt32ForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> UInt64
+/**
+ * Class used for map fields of <uint32_t, uint64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32UInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt64:(uint64_t)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt64s:(const uint64_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32UInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(uint32_t key, uint64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32UInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt64:(uint64_t)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt64ForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Int64
+/**
+ * Class used for map fields of <uint32_t, int64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32Int64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt64:(int64_t)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32Int64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt64s:(const int64_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32Int64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt64:(nullable int64_t *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(uint32_t key, int64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32Int64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt64:(int64_t)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt64ForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Bool
+/**
+ * Class used for map fields of <uint32_t, BOOL>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32BoolDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithBool:(BOOL)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithBools:(const BOOL [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32BoolDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithBools:(const BOOL [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32BoolDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getBool:(nullable BOOL *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(uint32_t key, BOOL value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32BoolDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setBool:(BOOL)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeBoolForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Float
+/**
+ * Class used for map fields of <uint32_t, float>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32FloatDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithFloat:(float)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithFloats:(const float [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32FloatDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithFloats:(const float [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32FloatDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getFloat:(nullable float *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(uint32_t key, float value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32FloatDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setFloat:(float)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeFloatForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Double
+/**
+ * Class used for map fields of <uint32_t, double>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32DoubleDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithDouble:(double)value
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithDoubles:(const double [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32DoubleDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithDoubles:(const double [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32DoubleDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getDouble:(nullable double *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(uint32_t key, double value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32DoubleDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setDouble:(double)value forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeDoubleForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Enum
+/**
+ * Class used for map fields of <uint32_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32EnumDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly instanced dictionary.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param rawValue The raw enum value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)rawValue
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32EnumDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
+/**
+ * Initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly initialized dictionary.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly initialized dictionary with the keys and values in it.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly initialized dictionary with the entries from the given
+ * dictionary in it.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32EnumDictionary *)dictionary;
+
+/**
+ * Initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly initialized dictionary with the given capacity.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
@@ -343,23 +1183,63 @@ NS_ASSUME_NONNULL_BEGIN
// is not a valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getEnum:(nullable int32_t *)value forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(uint32_t key, int32_t value, BOOL *stop))block;
-// These methods bypass the validationFunc to provide access to values that were not
-// known at the time the binary was compiled.
-
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **rawValue**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(uint32_t key, int32_t rawValue, BOOL *stop))block;
+/**
+ * Adds the keys and raw enum values from another dictionary.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addRawEntriesFromDictionary:(GPBUInt32EnumDictionary *)otherDictionary;
// If value is not a valid enumerator as defined by validationFunc, these
@@ -367,339 +1247,1312 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setEnum:(int32_t)value forKey:(uint32_t)key;
-// This method bypass the validationFunc to provide setting of values that were not
-// known at the time the binary was compiled.
+/**
+ * Sets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue The raw enum value to set.
+ * @param key The key under which to store the raw enum value.
+ **/
- (void)setRawValue:(int32_t)rawValue forKey:(uint32_t)key;
-// No validation applies to these methods.
-
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeEnumForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt32 -> Object
+/**
+ * Class used for map fields of <uint32_t, ObjectType>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt32ObjectDictionary<__covariant ObjectType> : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param object The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithObject:(ObjectType)object
forKey:(uint32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param objects The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const uint32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt32ObjectDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param objects The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const uint32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt32ObjectDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
+/**
+ * Fetches the object stored under the given key.
+ *
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return The object if found, nil otherwise.
+ **/
- (ObjectType)objectForKey:(uint32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **object**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(uint32_t key, ObjectType object, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt32ObjectDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param object The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setObject:(ObjectType)object forKey:(uint32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeObjectForKey:(uint32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> UInt32
+/**
+ * Class used for map fields of <int32_t, uint32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32UInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt32:(uint32_t)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt32s:(const uint32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32UInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(int32_t key, uint32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32UInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt32:(uint32_t)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt32ForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Int32
+/**
+ * Class used for map fields of <int32_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32Int32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt32:(int32_t)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32Int32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt32s:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32Int32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt32:(nullable int32_t *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(int32_t key, int32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32Int32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt32:(int32_t)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt32ForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> UInt64
+/**
+ * Class used for map fields of <int32_t, uint64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32UInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt64:(uint64_t)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32UInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt64s:(const uint64_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32UInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(int32_t key, uint64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32UInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt64:(uint64_t)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt64ForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Int64
+/**
+ * Class used for map fields of <int32_t, int64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32Int64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt64:(int64_t)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32Int64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt64s:(const int64_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32Int64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt64:(nullable int64_t *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(int32_t key, int64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32Int64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt64:(int64_t)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt64ForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Bool
+/**
+ * Class used for map fields of <int32_t, BOOL>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32BoolDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithBool:(BOOL)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithBools:(const BOOL [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32BoolDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithBools:(const BOOL [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32BoolDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getBool:(nullable BOOL *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(int32_t key, BOOL value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32BoolDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setBool:(BOOL)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeBoolForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Float
+/**
+ * Class used for map fields of <int32_t, float>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32FloatDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithFloat:(float)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithFloats:(const float [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32FloatDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithFloats:(const float [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32FloatDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getFloat:(nullable float *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(int32_t key, float value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32FloatDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setFloat:(float)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeFloatForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Double
+/**
+ * Class used for map fields of <int32_t, double>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32DoubleDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithDouble:(double)value
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithDoubles:(const double [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32DoubleDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithDoubles:(const double [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32DoubleDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getDouble:(nullable double *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(int32_t key, double value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32DoubleDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setDouble:(double)value forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeDoubleForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Enum
+/**
+ * Class used for map fields of <int32_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32EnumDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly instanced dictionary.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param rawValue The raw enum value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)rawValue
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32EnumDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
+/**
+ * Initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly initialized dictionary.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly initialized dictionary with the keys and values in it.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly initialized dictionary with the entries from the given
+ * dictionary in it.
+ **/
- (instancetype)initWithDictionary:(GPBInt32EnumDictionary *)dictionary;
+
+/**
+ * Initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly initialized dictionary with the given capacity.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
@@ -707,23 +2560,63 @@ NS_ASSUME_NONNULL_BEGIN
// is not a valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getEnum:(nullable int32_t *)value forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(int32_t key, int32_t value, BOOL *stop))block;
-// These methods bypass the validationFunc to provide access to values that were not
-// known at the time the binary was compiled.
-
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **rawValue**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(int32_t key, int32_t rawValue, BOOL *stop))block;
+/**
+ * Adds the keys and raw enum values from another dictionary.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addRawEntriesFromDictionary:(GPBInt32EnumDictionary *)otherDictionary;
// If value is not a valid enumerator as defined by validationFunc, these
@@ -731,339 +2624,1312 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setEnum:(int32_t)value forKey:(int32_t)key;
-// This method bypass the validationFunc to provide setting of values that were not
-// known at the time the binary was compiled.
+/**
+ * Sets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue The raw enum value to set.
+ * @param key The key under which to store the raw enum value.
+ **/
- (void)setRawValue:(int32_t)rawValue forKey:(int32_t)key;
-// No validation applies to these methods.
-
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeEnumForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int32 -> Object
+/**
+ * Class used for map fields of <int32_t, ObjectType>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt32ObjectDictionary<__covariant ObjectType> : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param object The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithObject:(ObjectType)object
forKey:(int32_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param objects The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const int32_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt32ObjectDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param objects The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const int32_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt32ObjectDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
+/**
+ * Fetches the object stored under the given key.
+ *
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return The object if found, nil otherwise.
+ **/
- (ObjectType)objectForKey:(int32_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **object**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(int32_t key, ObjectType object, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt32ObjectDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param object The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setObject:(ObjectType)object forKey:(int32_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeObjectForKey:(int32_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> UInt32
+/**
+ * Class used for map fields of <uint64_t, uint32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64UInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt32:(uint32_t)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt32s:(const uint32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64UInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(uint64_t key, uint32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64UInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt32:(uint32_t)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt32ForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Int32
+/**
+ * Class used for map fields of <uint64_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64Int32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt32:(int32_t)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt32s:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64Int32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt32:(nullable int32_t *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(uint64_t key, int32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64Int32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt32:(int32_t)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt32ForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> UInt64
+/**
+ * Class used for map fields of <uint64_t, uint64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64UInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt64:(uint64_t)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt64s:(const uint64_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64UInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(uint64_t key, uint64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64UInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt64:(uint64_t)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt64ForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Int64
+/**
+ * Class used for map fields of <uint64_t, int64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64Int64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt64:(int64_t)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64Int64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt64s:(const int64_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64Int64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt64:(nullable int64_t *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(uint64_t key, int64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64Int64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt64:(int64_t)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt64ForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Bool
+/**
+ * Class used for map fields of <uint64_t, BOOL>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64BoolDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithBool:(BOOL)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithBools:(const BOOL [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64BoolDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithBools:(const BOOL [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64BoolDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getBool:(nullable BOOL *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(uint64_t key, BOOL value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64BoolDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setBool:(BOOL)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeBoolForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Float
+/**
+ * Class used for map fields of <uint64_t, float>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64FloatDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithFloat:(float)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithFloats:(const float [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64FloatDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithFloats:(const float [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64FloatDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getFloat:(nullable float *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(uint64_t key, float value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64FloatDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setFloat:(float)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeFloatForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Double
+/**
+ * Class used for map fields of <uint64_t, double>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64DoubleDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithDouble:(double)value
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithDoubles:(const double [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64DoubleDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithDoubles:(const double [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64DoubleDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getDouble:(nullable double *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(uint64_t key, double value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64DoubleDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setDouble:(double)value forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeDoubleForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Enum
+/**
+ * Class used for map fields of <uint64_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64EnumDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly instanced dictionary.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param rawValue The raw enum value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)rawValue
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64EnumDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
+/**
+ * Initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly initialized dictionary.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly initialized dictionary with the keys and values in it.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly initialized dictionary with the entries from the given
+ * dictionary in it.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64EnumDictionary *)dictionary;
+
+/**
+ * Initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly initialized dictionary with the given capacity.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
@@ -1071,23 +3937,63 @@ NS_ASSUME_NONNULL_BEGIN
// is not a valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getEnum:(nullable int32_t *)value forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(uint64_t key, int32_t value, BOOL *stop))block;
-// These methods bypass the validationFunc to provide access to values that were not
-// known at the time the binary was compiled.
-
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **rawValue**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(uint64_t key, int32_t rawValue, BOOL *stop))block;
+/**
+ * Adds the keys and raw enum values from another dictionary.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addRawEntriesFromDictionary:(GPBUInt64EnumDictionary *)otherDictionary;
// If value is not a valid enumerator as defined by validationFunc, these
@@ -1095,339 +4001,1312 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setEnum:(int32_t)value forKey:(uint64_t)key;
-// This method bypass the validationFunc to provide setting of values that were not
-// known at the time the binary was compiled.
+/**
+ * Sets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue The raw enum value to set.
+ * @param key The key under which to store the raw enum value.
+ **/
- (void)setRawValue:(int32_t)rawValue forKey:(uint64_t)key;
-// No validation applies to these methods.
-
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeEnumForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - UInt64 -> Object
+/**
+ * Class used for map fields of <uint64_t, ObjectType>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBUInt64ObjectDictionary<__covariant ObjectType> : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param object The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithObject:(ObjectType)object
forKey:(uint64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param objects The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const uint64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBUInt64ObjectDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param objects The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const uint64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBUInt64ObjectDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
+/**
+ * Fetches the object stored under the given key.
+ *
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return The object if found, nil otherwise.
+ **/
- (ObjectType)objectForKey:(uint64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **object**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(uint64_t key, ObjectType object, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBUInt64ObjectDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param object The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setObject:(ObjectType)object forKey:(uint64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeObjectForKey:(uint64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> UInt32
+/**
+ * Class used for map fields of <int64_t, uint32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64UInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt32:(uint32_t)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt32s:(const uint32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64UInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(int64_t key, uint32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64UInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt32:(uint32_t)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt32ForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Int32
+/**
+ * Class used for map fields of <int64_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64Int32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt32:(int32_t)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64Int32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt32s:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64Int32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt32:(nullable int32_t *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(int64_t key, int32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64Int32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt32:(int32_t)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt32ForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> UInt64
+/**
+ * Class used for map fields of <int64_t, uint64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64UInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt64:(uint64_t)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64UInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt64s:(const uint64_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64UInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(int64_t key, uint64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64UInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt64:(uint64_t)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt64ForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Int64
+/**
+ * Class used for map fields of <int64_t, int64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64Int64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt64:(int64_t)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64Int64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt64s:(const int64_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64Int64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt64:(nullable int64_t *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(int64_t key, int64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64Int64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt64:(int64_t)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt64ForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Bool
+/**
+ * Class used for map fields of <int64_t, BOOL>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64BoolDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithBool:(BOOL)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithBools:(const BOOL [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64BoolDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithBools:(const BOOL [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64BoolDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getBool:(nullable BOOL *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(int64_t key, BOOL value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64BoolDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setBool:(BOOL)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeBoolForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Float
+/**
+ * Class used for map fields of <int64_t, float>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64FloatDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithFloat:(float)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithFloats:(const float [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64FloatDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithFloats:(const float [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64FloatDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getFloat:(nullable float *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(int64_t key, float value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64FloatDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setFloat:(float)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeFloatForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Double
+/**
+ * Class used for map fields of <int64_t, double>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64DoubleDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithDouble:(double)value
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithDoubles:(const double [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64DoubleDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithDoubles:(const double [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64DoubleDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getDouble:(nullable double *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(int64_t key, double value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64DoubleDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setDouble:(double)value forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeDoubleForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Enum
+/**
+ * Class used for map fields of <int64_t, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64EnumDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly instanced dictionary.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param rawValue The raw enum value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)rawValue
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64EnumDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
+/**
+ * Initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly initialized dictionary.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly initialized dictionary with the keys and values in it.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly initialized dictionary with the entries from the given
+ * dictionary in it.
+ **/
- (instancetype)initWithDictionary:(GPBInt64EnumDictionary *)dictionary;
+
+/**
+ * Initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly initialized dictionary with the given capacity.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
@@ -1435,23 +5314,63 @@ NS_ASSUME_NONNULL_BEGIN
// is not a valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getEnum:(nullable int32_t *)value forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(int64_t key, int32_t value, BOOL *stop))block;
-// These methods bypass the validationFunc to provide access to values that were not
-// known at the time the binary was compiled.
-
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **rawValue**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(int64_t key, int32_t rawValue, BOOL *stop))block;
+/**
+ * Adds the keys and raw enum values from another dictionary.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addRawEntriesFromDictionary:(GPBInt64EnumDictionary *)otherDictionary;
// If value is not a valid enumerator as defined by validationFunc, these
@@ -1459,339 +5378,1312 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setEnum:(int32_t)value forKey:(int64_t)key;
-// This method bypass the validationFunc to provide setting of values that were not
-// known at the time the binary was compiled.
+/**
+ * Sets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue The raw enum value to set.
+ * @param key The key under which to store the raw enum value.
+ **/
- (void)setRawValue:(int32_t)rawValue forKey:(int64_t)key;
-// No validation applies to these methods.
-
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeEnumForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Int64 -> Object
+/**
+ * Class used for map fields of <int64_t, ObjectType>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBInt64ObjectDictionary<__covariant ObjectType> : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param object The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithObject:(ObjectType)object
forKey:(int64_t)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param objects The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const int64_t [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBInt64ObjectDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param objects The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const int64_t [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBInt64ObjectDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
+/**
+ * Fetches the object stored under the given key.
+ *
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return The object if found, nil otherwise.
+ **/
- (ObjectType)objectForKey:(int64_t)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **object**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(int64_t key, ObjectType object, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBInt64ObjectDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param object The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setObject:(ObjectType)object forKey:(int64_t)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeObjectForKey:(int64_t)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> UInt32
+/**
+ * Class used for map fields of <BOOL, uint32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolUInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt32:(uint32_t)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt32s:(const uint32_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolUInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(BOOL key, uint32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolUInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt32:(uint32_t)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt32ForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Int32
+/**
+ * Class used for map fields of <BOOL, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt32:(int32_t)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt32s:(const int32_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt32:(nullable int32_t *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(BOOL key, int32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt32:(int32_t)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt32ForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> UInt64
+/**
+ * Class used for map fields of <BOOL, uint64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolUInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt64:(uint64_t)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolUInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt64s:(const uint64_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolUInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(BOOL key, uint64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolUInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt64:(uint64_t)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt64ForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Int64
+/**
+ * Class used for map fields of <BOOL, int64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt64:(int64_t)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt64s:(const int64_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt64:(nullable int64_t *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(BOOL key, int64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt64:(int64_t)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt64ForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Bool
+/**
+ * Class used for map fields of <BOOL, BOOL>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolBoolDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithBool:(BOOL)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithBools:(const BOOL [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolBoolDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithBools:(const BOOL [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolBoolDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getBool:(nullable BOOL *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(BOOL key, BOOL value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolBoolDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setBool:(BOOL)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeBoolForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Float
+/**
+ * Class used for map fields of <BOOL, float>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolFloatDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithFloat:(float)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithFloats:(const float [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolFloatDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithFloats:(const float [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolFloatDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getFloat:(nullable float *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(BOOL key, float value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolFloatDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setFloat:(float)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeFloatForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Double
+/**
+ * Class used for map fields of <BOOL, double>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolDoubleDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithDouble:(double)value
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithDoubles:(const double [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolDoubleDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithDoubles:(const double [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolDoubleDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getDouble:(nullable double *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(BOOL key, double value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolDoubleDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setDouble:(double)value forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeDoubleForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Enum
+/**
+ * Class used for map fields of <BOOL, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolEnumDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly instanced dictionary.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param rawValue The raw enum value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)rawValue
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolEnumDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
+/**
+ * Initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly initialized dictionary.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly initialized dictionary with the keys and values in it.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly initialized dictionary with the entries from the given
+ * dictionary in it.
+ **/
- (instancetype)initWithDictionary:(GPBBoolEnumDictionary *)dictionary;
+
+/**
+ * Initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly initialized dictionary with the given capacity.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
@@ -1799,23 +6691,63 @@ NS_ASSUME_NONNULL_BEGIN
// is not a valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getEnum:(nullable int32_t *)value forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(BOOL key, int32_t value, BOOL *stop))block;
-// These methods bypass the validationFunc to provide access to values that were not
-// known at the time the binary was compiled.
-
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **rawValue**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(BOOL key, int32_t rawValue, BOOL *stop))block;
+/**
+ * Adds the keys and raw enum values from another dictionary.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addRawEntriesFromDictionary:(GPBBoolEnumDictionary *)otherDictionary;
// If value is not a valid enumerator as defined by validationFunc, these
@@ -1823,339 +6755,1312 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setEnum:(int32_t)value forKey:(BOOL)key;
-// This method bypass the validationFunc to provide setting of values that were not
-// known at the time the binary was compiled.
+/**
+ * Sets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue The raw enum value to set.
+ * @param key The key under which to store the raw enum value.
+ **/
- (void)setRawValue:(int32_t)rawValue forKey:(BOOL)key;
-// No validation applies to these methods.
-
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeEnumForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - Bool -> Object
+/**
+ * Class used for map fields of <BOOL, ObjectType>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBBoolObjectDictionary<__covariant ObjectType> : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param object The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithObject:(ObjectType)object
forKey:(BOOL)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param objects The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const BOOL [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBBoolObjectDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param objects The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithObjects:(const ObjectType GPB_UNSAFE_UNRETAINED [])objects
forKeys:(const BOOL [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBBoolObjectDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
+/**
+ * Fetches the object stored under the given key.
+ *
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return The object if found, nil otherwise.
+ **/
- (ObjectType)objectForKey:(BOOL)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **object**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndObjectsUsingBlock:
(void (^)(BOOL key, ObjectType object, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBBoolObjectDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param object The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setObject:(ObjectType)object forKey:(BOOL)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeObjectForKey:(BOOL)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> UInt32
+/**
+ * Class used for map fields of <NSString, uint32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringUInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt32:(uint32_t)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt32s:(const uint32_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringUInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt32s:(const uint32_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringUInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt32:(nullable uint32_t *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt32sUsingBlock:
(void (^)(NSString *key, uint32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringUInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt32:(uint32_t)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt32ForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> Int32
+/**
+ * Class used for map fields of <NSString, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringInt32Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt32:(int32_t)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt32s:(const int32_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringInt32Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt32s:(const int32_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringInt32Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt32:(nullable int32_t *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt32sUsingBlock:
(void (^)(NSString *key, int32_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringInt32Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt32:(int32_t)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt32ForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> UInt64
+/**
+ * Class used for map fields of <NSString, uint64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringUInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithUInt64:(uint64_t)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithUInt64s:(const uint64_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringUInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithUInt64s:(const uint64_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringUInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getUInt64:(nullable uint64_t *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndUInt64sUsingBlock:
(void (^)(NSString *key, uint64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringUInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setUInt64:(uint64_t)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeUInt64ForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> Int64
+/**
+ * Class used for map fields of <NSString, int64_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringInt64Dictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithInt64:(int64_t)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithInt64s:(const int64_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringInt64Dictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithInt64s:(const int64_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringInt64Dictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getInt64:(nullable int64_t *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndInt64sUsingBlock:
(void (^)(NSString *key, int64_t value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringInt64Dictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setInt64:(int64_t)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeInt64ForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> Bool
+/**
+ * Class used for map fields of <NSString, BOOL>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringBoolDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithBool:(BOOL)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithBools:(const BOOL [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringBoolDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithBools:(const BOOL [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringBoolDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getBool:(nullable BOOL *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndBoolsUsingBlock:
(void (^)(NSString *key, BOOL value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringBoolDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setBool:(BOOL)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeBoolForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> Float
+/**
+ * Class used for map fields of <NSString, float>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringFloatDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithFloat:(float)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithFloats:(const float [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringFloatDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithFloats:(const float [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringFloatDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getFloat:(nullable float *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndFloatsUsingBlock:
(void (^)(NSString *key, float value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringFloatDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setFloat:(float)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeFloatForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> Double
+/**
+ * Class used for map fields of <NSString, double>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringDoubleDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param value The value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithDouble:(double)value
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param values The values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithDoubles:(const double [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringDoubleDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
+/**
+ * Initializes this dictionary, copying the given values and keys.
+ *
+ * @param values The values to be placed in this dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of elements to copy into the dictionary.
+ *
+ * @return A newly initialized dictionary with a copy of the values and keys.
+ **/
- (instancetype)initWithDoubles:(const double [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes this dictionary, copying the entries from the given dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to this dictionary.
+ *
+ * @return A newly initialized dictionary with the entries of the given dictionary.
+ **/
- (instancetype)initWithDictionary:(GPBStringDoubleDictionary *)dictionary;
+
+/**
+ * Initializes this dictionary with the requested capacity.
+ *
+ * @param numItems Number of items needed for this dictionary.
+ *
+ * @return A newly initialized dictionary with the requested capacity.
+ **/
- (instancetype)initWithCapacity:(NSUInteger)numItems;
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getDouble:(nullable double *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndDoublesUsingBlock:
(void (^)(NSString *key, double value, BOOL *stop))block;
+/**
+ * Adds the keys and values from another dictionary.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addEntriesFromDictionary:(GPBStringDoubleDictionary *)otherDictionary;
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setDouble:(double)value forKey:(NSString *)key;
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeDoubleForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
#pragma mark - String -> Enum
+/**
+ * Class used for map fields of <NSString, int32_t>
+ * values. This performs better than boxing into NSNumbers in NSDictionaries.
+ *
+ * @note This class is not meant to be subclassed.
+ **/
@interface GPBStringEnumDictionary : NSObject <NSCopying>
+/** Number of entries stored in this dictionary. */
@property(nonatomic, readonly) NSUInteger count;
+/** The validation function to check if the enums are valid. */
@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
+/**
+ * @return A newly instanced and empty dictionary.
+ **/
+ (instancetype)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly instanced dictionary.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Creates and initializes a dictionary with the single entry given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param rawValue The raw enum value to be placed in the dictionary.
+ * @param key The key under which to store the value.
+ *
+ * @return A newly instanced dictionary with the key and value in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValue:(int32_t)rawValue
forKey:(NSString *)key;
+
+/**
+ * Creates and initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly instanced dictionary with the keys and values in it.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count;
+
+/**
+ * Creates and initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly instanced dictionary with the entries from the given
+ * dictionary in it.
+ **/
+ (instancetype)dictionaryWithDictionary:(GPBStringEnumDictionary *)dictionary;
+
+/**
+ * Creates and initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly instanced dictionary with the given capacity.
+ **/
+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
+/**
+ * Initializes a dictionary with the given validation function.
+ *
+ * @param func The enum validation function for the dictionary.
+ *
+ * @return A newly initialized dictionary.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+
+/**
+ * Initializes a dictionary with the entries given.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param values The raw enum values values to be placed in the dictionary.
+ * @param keys The keys under which to store the values.
+ * @param count The number of entries to store in the dictionary.
+ *
+ * @return A newly initialized dictionary with the keys and values in it.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
rawValues:(const int32_t [])values
forKeys:(const NSString * GPB_UNSAFE_UNRETAINED [])keys
count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+
+/**
+ * Initializes a dictionary with the entries from the given.
+ * dictionary.
+ *
+ * @param dictionary Dictionary containing the entries to add to the dictionary.
+ *
+ * @return A newly initialized dictionary with the entries from the given
+ * dictionary in it.
+ **/
- (instancetype)initWithDictionary:(GPBStringEnumDictionary *)dictionary;
+
+/**
+ * Initializes a dictionary with the given capacity.
+ *
+ * @param func The enum validation function for the dictionary.
+ * @param numItems Capacity needed for the dictionary.
+ *
+ * @return A newly initialized dictionary with the given capacity.
+ **/
- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
capacity:(NSUInteger)numItems;
@@ -2163,23 +8068,63 @@ NS_ASSUME_NONNULL_BEGIN
// is not a valid enumerator as defined by validationFunc. If the actual value is
// desired, use "raw" version of the method.
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the value for the given key.
+ *
+ * @param value Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getEnum:(nullable int32_t *)value forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **value**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndEnumsUsingBlock:
(void (^)(NSString *key, int32_t value, BOOL *stop))block;
-// These methods bypass the validationFunc to provide access to values that were not
-// known at the time the binary was compiled.
-
-// Returns YES/NO to indicate if the key was found or not, filling in the value
-// only when the key was found.
+/**
+ * Gets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue Pointer into which the value will be set, if found.
+ * @param key Key under which the value is stored, if present.
+ *
+ * @return YES if the key was found and the value was copied, NO otherwise.
+ **/
- (BOOL)getRawValue:(nullable int32_t *)rawValue forKey:(NSString *)key;
+/**
+ * Enumerates the keys and values on this dictionary with the given block.
+ *
+ * @note This method bypass the validationFunc to enable the access of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param block The block to enumerate with.
+ * **key**: The key for the current entry.
+ * **rawValue**: The value for the current entry
+ * **stop**: A pointer to a boolean that when set stops the enumeration.
+ **/
- (void)enumerateKeysAndRawValuesUsingBlock:
(void (^)(NSString *key, int32_t rawValue, BOOL *stop))block;
+/**
+ * Adds the keys and raw enum values from another dictionary.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param otherDictionary Dictionary containing entries to be added to this
+ * dictionary.
+ **/
- (void)addRawEntriesFromDictionary:(GPBStringEnumDictionary *)otherDictionary;
// If value is not a valid enumerator as defined by validationFunc, these
@@ -2187,15 +8132,35 @@ NS_ASSUME_NONNULL_BEGIN
// to the default value. Use the rawValue methods below to assign non enumerator
// values.
+/**
+ * Sets the value for the given key.
+ *
+ * @param value The value to set.
+ * @param key The key under which to store the value.
+ **/
- (void)setEnum:(int32_t)value forKey:(NSString *)key;
-// This method bypass the validationFunc to provide setting of values that were not
-// known at the time the binary was compiled.
+/**
+ * Sets the raw enum value for the given key.
+ *
+ * @note This method bypass the validationFunc to enable the setting of values that
+ * were not known at the time the binary was compiled.
+ *
+ * @param rawValue The raw enum value to set.
+ * @param key The key under which to store the raw enum value.
+ **/
- (void)setRawValue:(int32_t)rawValue forKey:(NSString *)key;
-// No validation applies to these methods.
-
+/**
+ * Removes the entry for the given key.
+ *
+ * @param aKey Key to be removed from this dictionary.
+ **/
- (void)removeEnumForKey:(NSString *)aKey;
+
+/**
+ * Removes all entries in this dictionary.
+ **/
- (void)removeAll;
@end
@@ -2228,10 +8193,23 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE DICTIONARY_POD_KEY_TO_OBJECT_INTERFACE(KEY_NAME, KEY_TYPE, VALUE_NAME, VALUE_TYPE)
//%DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, , POD, VALUE_NAME, VALUE_TYPE, OBJECT, Object, object)
//%PDDM-DEFINE VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME)
-//%// Returns YES/NO to indicate if the key was found or not, filling in the value
-//%// only when the key was found.
+//%/**
+//% * Gets the value for the given key.
+//% *
+//% * @param value Pointer into which the value will be set, if found.
+//% * @param key Key under which the value is stored, if present.
+//% *
+//% * @return YES if the key was found and the value was copied, NO otherwise.
+//% **/
//%- (BOOL)get##VNAME##:(nullable VALUE_TYPE *)value forKey:(KEY_TYPE)key;
//%PDDM-DEFINE VALUE_FOR_KEY_OBJECT(KEY_TYPE, VALUE_TYPE, VNAME)
+//%/**
+//% * Fetches the object stored under the given key.
+//% *
+//% * @param key Key under which the value is stored, if present.
+//% *
+//% * @return The object if found, nil otherwise.
+//% **/
//%- (VALUE_TYPE)objectForKey:(KEY_TYPE)key;
//%PDDM-DEFINE VALUE_FOR_KEY_Enum(KEY_TYPE, VALUE_TYPE, VNAME)
//%VALUE_FOR_KEY_POD(KEY_TYPE, VALUE_TYPE, VNAME)
@@ -2250,27 +8228,105 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE DICTIONARY_COMMON_INTERFACE(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR)
//%#pragma mark - KEY_NAME -> VALUE_NAME
//%
+//%/**
+//% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##>
+//% * values. This performs better than boxing into NSNumbers in NSDictionaries.
+//% *
+//% * @note This class is not meant to be subclassed.
+//% **/
//%@interface DICTIONARY_CLASS_DECL##VHELPER(KEY_NAME, VALUE_NAME, VALUE_TYPE) : NSObject <NSCopying>
//%
+//%/** Number of entries stored in this dictionary. */
//%@property(nonatomic, readonly) NSUInteger count;
//%
+//%/**
+//% * @return A newly instanced and empty dictionary.
+//% **/
//%+ (instancetype)dictionary;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the single entry given.
+//% *
+//% * @param ##VNAME_VAR The value to be placed in the dictionary.
+//% * @param key ##VNAME_VAR$S## The key under which to store the value.
+//% *
+//% * @return A newly instanced dictionary with the key and value in it.
+//% **/
//%+ (instancetype)dictionaryWith##VNAME##:(VALUE_TYPE)##VNAME_VAR
//% ##VNAME$S## forKey:(KEY_TYPE##KisP$S##KisP)key;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the entries given.
+//% *
+//% * @param ##VNAME_VAR##s The values to be placed in the dictionary.
+//% * @param keys ##VNAME_VAR$S## The keys under which to store the values.
+//% * @param count ##VNAME_VAR$S## The number of entries to store in the dictionary.
+//% *
+//% * @return A newly instanced dictionary with the keys and values in it.
+//% **/
//%+ (instancetype)dictionaryWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])##VNAME_VAR##s
//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
//% ##VNAME$S## count:(NSUInteger)count;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the entries from the given.
+//% * dictionary.
+//% *
+//% * @param dictionary Dictionary containing the entries to add to the dictionary.
+//% *
+//% * @return A newly instanced dictionary with the entries from the given
+//% * dictionary in it.
+//% **/
//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the given capacity.
+//% *
+//% * @param numItems Capacity needed for the dictionary.
+//% *
+//% * @return A newly instanced dictionary with the given capacity.
+//% **/
//%+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems;
//%
+//%/**
+//% * Initializes this dictionary, copying the given values and keys.
+//% *
+//% * @param ##VNAME_VAR##s The values to be placed in this dictionary.
+//% * @param keys ##VNAME_VAR$S## The keys under which to store the values.
+//% * @param count ##VNAME_VAR$S## The number of elements to copy into the dictionary.
+//% *
+//% * @return A newly initialized dictionary with a copy of the values and keys.
+//% **/
//%- (instancetype)initWith##VNAME##s:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])##VNAME_VAR##s
//% ##VNAME$S## forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
//% ##VNAME$S## count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+//%
+//%/**
+//% * Initializes this dictionary, copying the entries from the given dictionary.
+//% *
+//% * @param dictionary Dictionary containing the entries to add to this dictionary.
+//% *
+//% * @return A newly initialized dictionary with the entries of the given dictionary.
+//% **/
//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
+//%
+//%/**
+//% * Initializes this dictionary with the requested capacity.
+//% *
+//% * @param numItems Number of items needed for this dictionary.
+//% *
+//% * @return A newly initialized dictionary with the requested capacity.
+//% **/
//%- (instancetype)initWithCapacity:(NSUInteger)numItems;
//%
//%DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR)
//%
+//%/**
+//% * Adds the keys and values from another dictionary.
+//% *
+//% * @param otherDictionary Dictionary containing entries to be added to this
+//% * dictionary.
+//% **/
//%- (void)addEntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary;
//%
//%DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR)
@@ -2283,30 +8339,126 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE DICTIONARY_KEY_TO_ENUM_INTERFACE2(KEY_NAME, KEY_TYPE, KisP, KHELPER, VALUE_NAME, VALUE_TYPE, VHELPER)
//%#pragma mark - KEY_NAME -> VALUE_NAME
//%
+//%/**
+//% * Class used for map fields of <##KEY_TYPE##, ##VALUE_TYPE##>
+//% * values. This performs better than boxing into NSNumbers in NSDictionaries.
+//% *
+//% * @note This class is not meant to be subclassed.
+//% **/
//%@interface GPB##KEY_NAME##VALUE_NAME##Dictionary : NSObject <NSCopying>
//%
+//%/** Number of entries stored in this dictionary. */
//%@property(nonatomic, readonly) NSUInteger count;
+//%/** The validation function to check if the enums are valid. */
//%@property(nonatomic, readonly) GPBEnumValidationFunc validationFunc;
//%
+//%/**
+//% * @return A newly instanced and empty dictionary.
+//% **/
//%+ (instancetype)dictionary;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the given validation function.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% *
+//% * @return A newly instanced dictionary.
+//% **/
//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the single entry given.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% * @param rawValue The raw enum value to be placed in the dictionary.
+//% * @param key The key under which to store the value.
+//% *
+//% * @return A newly instanced dictionary with the key and value in it.
+//% **/
//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% rawValue:(VALUE_TYPE)rawValue
//% forKey:(KEY_TYPE##KisP$S##KisP)key;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the entries given.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% * @param values The raw enum values values to be placed in the dictionary.
+//% * @param keys The keys under which to store the values.
+//% * @param count The number of entries to store in the dictionary.
+//% *
+//% * @return A newly instanced dictionary with the keys and values in it.
+//% **/
//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])values
//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
//% count:(NSUInteger)count;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the entries from the given.
+//% * dictionary.
+//% *
+//% * @param dictionary Dictionary containing the entries to add to the dictionary.
+//% *
+//% * @return A newly instanced dictionary with the entries from the given
+//% * dictionary in it.
+//% **/
//%+ (instancetype)dictionaryWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
+//%
+//%/**
+//% * Creates and initializes a dictionary with the given capacity.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% * @param numItems Capacity needed for the dictionary.
+//% *
+//% * @return A newly instanced dictionary with the given capacity.
+//% **/
//%+ (instancetype)dictionaryWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% capacity:(NSUInteger)numItems;
//%
+//%/**
+//% * Initializes a dictionary with the given validation function.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% *
+//% * @return A newly initialized dictionary.
+//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func;
+//%
+//%/**
+//% * Initializes a dictionary with the entries given.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% * @param values The raw enum values values to be placed in the dictionary.
+//% * @param keys The keys under which to store the values.
+//% * @param count The number of entries to store in the dictionary.
+//% *
+//% * @return A newly initialized dictionary with the keys and values in it.
+//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% rawValues:(const VALUE_TYPE ARRAY_ARG_MODIFIER##VHELPER()[])values
//% forKeys:(const KEY_TYPE##KisP$S##KisP ARRAY_ARG_MODIFIER##KHELPER()[])keys
//% count:(NSUInteger)count NS_DESIGNATED_INITIALIZER;
+//%
+//%/**
+//% * Initializes a dictionary with the entries from the given.
+//% * dictionary.
+//% *
+//% * @param dictionary Dictionary containing the entries to add to the dictionary.
+//% *
+//% * @return A newly initialized dictionary with the entries from the given
+//% * dictionary in it.
+//% **/
//%- (instancetype)initWithDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)dictionary;
+//%
+//%/**
+//% * Initializes a dictionary with the given capacity.
+//% *
+//% * @param func The enum validation function for the dictionary.
+//% * @param numItems Capacity needed for the dictionary.
+//% *
+//% * @return A newly initialized dictionary with the given capacity.
+//% **/
//%- (instancetype)initWithValidationFunction:(nullable GPBEnumValidationFunc)func
//% capacity:(NSUInteger)numItems;
//%
@@ -2316,16 +8468,42 @@ NS_ASSUME_NONNULL_END
//%
//%DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, Enum, value)
//%
-//%// These methods bypass the validationFunc to provide access to values that were not
-//%// known at the time the binary was compiled.
-//%
-//%// Returns YES/NO to indicate if the key was found or not, filling in the value
-//%// only when the key was found.
+//%/**
+//% * Gets the raw enum value for the given key.
+//% *
+//% * @note This method bypass the validationFunc to enable the access of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param rawValue Pointer into which the value will be set, if found.
+//% * @param key Key under which the value is stored, if present.
+//% *
+//% * @return YES if the key was found and the value was copied, NO otherwise.
+//% **/
//%- (BOOL)getRawValue:(nullable VALUE_TYPE *)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key;
//%
+//%/**
+//% * Enumerates the keys and values on this dictionary with the given block.
+//% *
+//% * @note This method bypass the validationFunc to enable the access of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param block The block to enumerate with.
+//% * **key**: The key for the current entry.
+//% * **rawValue**: The value for the current entry
+//% * **stop**: A pointer to a boolean that when set stops the enumeration.
+//% **/
//%- (void)enumerateKeysAndRawValuesUsingBlock:
//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE rawValue, BOOL *stop))block;
//%
+//%/**
+//% * Adds the keys and raw enum values from another dictionary.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param otherDictionary Dictionary containing entries to be added to this
+//% * dictionary.
+//% **/
//%- (void)addRawEntriesFromDictionary:(GPB##KEY_NAME##VALUE_NAME##Dictionary *)otherDictionary;
//%
//%// If value is not a valid enumerator as defined by validationFunc, these
@@ -2341,13 +8519,36 @@ NS_ASSUME_NONNULL_END
//%PDDM-DEFINE DICTIONARY_IMMUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR)
//%VALUE_FOR_KEY_##VHELPER(KEY_TYPE##KisP$S##KisP, VALUE_TYPE, VNAME)
//%
+//%/**
+//% * Enumerates the keys and values on this dictionary with the given block.
+//% *
+//% * @param block The block to enumerate with.
+//% * **key**: ##VNAME_VAR$S## The key for the current entry.
+//% * **VNAME_VAR**: The value for the current entry
+//% * **stop**: ##VNAME_VAR$S## A pointer to a boolean that when set stops the enumeration.
+//% **/
//%- (void)enumerateKeysAnd##VNAME##sUsingBlock:
//% (void (^)(KEY_TYPE KisP##key, VALUE_TYPE VNAME_VAR, BOOL *stop))block;
//%PDDM-DEFINE DICTIONARY_MUTABLE_INTERFACE(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE, VHELPER, VNAME, VNAME_VAR)
+//%/**
+//% * Sets the value for the given key.
+//% *
+//% * @param ##VNAME_VAR The value to set.
+//% * @param key ##VNAME_VAR$S## The key under which to store the value.
+//% **/
//%- (void)set##VNAME##:(VALUE_TYPE)##VNAME_VAR forKey:(KEY_TYPE##KisP$S##KisP)key;
//%DICTIONARY_EXTRA_MUTABLE_METHODS_##VHELPER(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE)
+//%/**
+//% * Removes the entry for the given key.
+//% *
+//% * @param aKey Key to be removed from this dictionary.
+//% **/
//%- (void)remove##VNAME##ForKey:(KEY_TYPE##KisP$S##KisP)aKey;
+//%
+//%/**
+//% * Removes all entries in this dictionary.
+//% **/
//%- (void)removeAll;
//%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_POD(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE)
@@ -2356,9 +8557,14 @@ NS_ASSUME_NONNULL_END
// Empty
//%PDDM-DEFINE DICTIONARY_EXTRA_MUTABLE_METHODS_Enum(KEY_NAME, KEY_TYPE, KisP, VALUE_NAME, VALUE_TYPE)
//%
-//%// This method bypass the validationFunc to provide setting of values that were not
-//%// known at the time the binary was compiled.
+//%/**
+//% * Sets the raw enum value for the given key.
+//% *
+//% * @note This method bypass the validationFunc to enable the setting of values that
+//% * were not known at the time the binary was compiled.
+//% *
+//% * @param rawValue The raw enum value to set.
+//% * @param key The key under which to store the raw enum value.
+//% **/
//%- (void)setRawValue:(VALUE_TYPE)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key;
//%
-//%// No validation applies to these methods.
-//%
diff --git a/objectivec/GPBExtensionRegistry.h b/objectivec/GPBExtensionRegistry.h
index 08a6472a..d79632d2 100644
--- a/objectivec/GPBExtensionRegistry.h
+++ b/objectivec/GPBExtensionRegistry.h
@@ -35,45 +35,50 @@
NS_ASSUME_NONNULL_BEGIN
-/// A table of known extensions, searchable by name or field number. When
-/// parsing a protocol message that might have extensions, you must provide a
-/// @c GPBExtensionRegistry in which you have registered any extensions that you
-/// want to be able to parse. Otherwise, those extensions will just be treated
-/// like unknown fields.
-///
-/// The @c *Root classes provide @c +extensionRegistry for the extensions defined
-/// in a given file *and* all files it imports. You can also create a
-/// @c GPBExtensionRegistry, and merge those registries to handle parsing
-/// extensions defined from non overlapping files.
-///
-/// @code
-/// GPBExtensionRegistry *registry =
-/// [[[MyProtoFileRoot extensionRegistry] copy] autorelease];
-/// [registry addExtension:[OtherMessage neededExtension]; // Not in MyProtoFile
-/// NSError *parseError = nil;
-/// MyMessage *msg = [MyMessage parseData:data
-/// extensionRegistry:registry
-/// error:&parseError];
-/// @endcode
+/**
+ * A table of known extensions, searchable by name or field number. When
+ * parsing a protocol message that might have extensions, you must provide a
+ * GPBExtensionRegistry in which you have registered any extensions that you
+ * want to be able to parse. Otherwise, those extensions will just be treated
+ * like unknown fields.
+ *
+ * The *Root classes provide `+extensionRegistry` for the extensions defined
+ * in a given file *and* all files it imports. You can also create a
+ * GPBExtensionRegistry, and merge those registries to handle parsing
+ * extensions defined from non overlapping files.
+ *
+ * ```
+ * GPBExtensionRegistry *registry = [[MyProtoFileRoot extensionRegistry] copy];
+ * [registry addExtension:[OtherMessage neededExtension]]; // Not in MyProtoFile
+ * NSError *parseError;
+ * MyMessage *msg = [MyMessage parseData:data extensionRegistry:registry error:&parseError];
+ * ```
+ **/
@interface GPBExtensionRegistry : NSObject<NSCopying>
-/// Add the given @c GPBExtensionDescriptor to this registry.
-///
-/// @param extension The extension description to add.
+/**
+ * Adds the given GPBExtensionDescriptor to this registry.
+ *
+ * @param extension The extension description to add.
+ **/
- (void)addExtension:(GPBExtensionDescriptor *)extension;
-/// Adds all the extensions from another registry to this registry.
-///
-/// @param registry The registry to merge into this registry.
+/**
+ * Adds all the extensions from another registry to this registry.
+ *
+ * @param registry The registry to merge into this registry.
+ **/
- (void)addExtensions:(GPBExtensionRegistry *)registry;
-/// Looks for the extension registered for the given field number on a given
-/// @c GPBDescriptor.
-///
-/// @param descriptor The descriptor to look for a registered extension on.
-/// @param fieldNumber The field number of an extension to look for.
-///
-/// @return The registered @c GPBExtensionDescripto or nil if none was found.
+/**
+ * Looks for the extension registered for the given field number on a given
+ * GPBDescriptor.
+ *
+ * @param descriptor The descriptor to look for a registered extension on.
+ * @param fieldNumber The field number of the extension to look for.
+ *
+ * @return The registered GPBExtensionDescriptor or nil if none was found.
+ **/
- (nullable GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor
fieldNumber:(NSInteger)fieldNumber;
diff --git a/objectivec/GPBExtensionRegistry.m b/objectivec/GPBExtensionRegistry.m
index 01eb761f..65534b67 100644
--- a/objectivec/GPBExtensionRegistry.m
+++ b/objectivec/GPBExtensionRegistry.m
@@ -34,8 +34,6 @@
#import "GPBDescriptor.h"
@implementation GPBExtensionRegistry {
- // TODO(dmaclach): Reimplement with CFDictionaries that don't use
- // objects as keys.
NSMutableDictionary *mutableClassMap_;
}
@@ -65,13 +63,16 @@
return result;
}
-- (NSMutableDictionary *)extensionMapForContainingMessageClass:
+- (CFMutableDictionaryRef)extensionMapForContainingMessageClass:
(Class)containingMessageClass {
- NSMutableDictionary *extensionMap =
+ CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)
[mutableClassMap_ objectForKey:containingMessageClass];
if (extensionMap == nil) {
- extensionMap = [NSMutableDictionary dictionary];
- [mutableClassMap_ setObject:extensionMap
+ // Use a custom dictionary here because the keys are numbers and conversion
+ // back and forth from NSNumber isn't worth the cost.
+ extensionMap = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL,
+ &kCFTypeDictionaryValueCallBacks);
+ [mutableClassMap_ setObject:(id)extensionMap
forKey:(id<NSCopying>)containingMessageClass];
}
return extensionMap;
@@ -83,17 +84,28 @@
}
Class containingMessageClass = extension.containingMessageClass;
- NSMutableDictionary *extensionMap =
+ CFMutableDictionaryRef extensionMap =
[self extensionMapForContainingMessageClass:containingMessageClass];
- [extensionMap setObject:extension forKey:@(extension.fieldNumber)];
+ ssize_t key = extension.fieldNumber;
+ CFDictionarySetValue(extensionMap, (const void *)key, extension);
}
- (GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor
fieldNumber:(NSInteger)fieldNumber {
Class messageClass = descriptor.messageClass;
- NSDictionary *extensionMap =
+ CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)
[mutableClassMap_ objectForKey:messageClass];
- return [extensionMap objectForKey:@(fieldNumber)];
+ ssize_t key = fieldNumber;
+ GPBExtensionDescriptor *result =
+ (extensionMap
+ ? CFDictionaryGetValue(extensionMap, (const void *)key)
+ : nil);
+ return result;
+}
+
+static void CopyKeyValue(const void *key, const void *value, void *context) {
+ CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef)context;
+ CFDictionarySetValue(extensionMap, key, value);
}
- (void)addExtensions:(GPBExtensionRegistry *)registry {
@@ -102,13 +114,16 @@
return;
}
NSMutableDictionary *otherClassMap = registry->mutableClassMap_;
- for (Class containingMessageClass in otherClassMap) {
- NSMutableDictionary *extensionMap =
+ [otherClassMap enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL * stop) {
+#pragma unused(stop)
+ Class containingMessageClass = key;
+ CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value;
+
+ CFMutableDictionaryRef extensionMap =
[self extensionMapForContainingMessageClass:containingMessageClass];
- NSMutableDictionary *otherExtensionMap =
- [registry extensionMapForContainingMessageClass:containingMessageClass];
- [extensionMap addEntriesFromDictionary:otherExtensionMap];
- }
+
+ CFDictionaryApplyFunction(otherExtensionMap, CopyKeyValue, extensionMap);
+ }];
}
#pragma clang diagnostic pop
diff --git a/objectivec/GPBMessage.h b/objectivec/GPBMessage.h
index 7e0f58a3..c07ec888 100644
--- a/objectivec/GPBMessage.h
+++ b/objectivec/GPBMessage.h
@@ -44,285 +44,413 @@ NS_ASSUME_NONNULL_BEGIN
CF_EXTERN_C_BEGIN
-/// NSError domain used for errors.
+/** NSError domain used for errors. */
extern NSString *const GPBMessageErrorDomain;
-/// Error code for NSError with GPBMessageErrorDomain.
+/** Error codes for NSErrors originated in GPBMessage. */
typedef NS_ENUM(NSInteger, GPBMessageErrorCode) {
- /// Uncategorized error.
+ /** Uncategorized error. */
GPBMessageErrorCodeOther = -100,
- /// A message can't be serialized because it is missing required fields.
+ /** Message couldn't be serialized because it is missing required fields. */
GPBMessageErrorCodeMissingRequiredField = -101,
};
-/// Key under which the error's reason is stored inside the userInfo dictionary.
+/**
+ * Key under which the GPBMessage error's reason is stored inside the userInfo
+ * dictionary.
+ **/
extern NSString *const GPBErrorReasonKey;
CF_EXTERN_C_END
-/// Base class for all of the generated message classes.
+/**
+ * Base class that each generated message subclasses from.
+ *
+ * @note While the class support NSSecureCoding, if the message has any
+ * extensions, they will end up reloaded in @c unknownFields as there is
+ * no way for the @c NSCoding plumbing to pass through a
+ * @c GPBExtensionRegistry. To support extensions, instead of passing the
+ * calls off to the Message, simple store the result of @c data, and then
+ * when loading, fetch the data and use
+ * @c +parseFromData:extensionRegistry:error: to provide an extension
+ * registry.
+ **/
@interface GPBMessage : NSObject<NSSecureCoding, NSCopying>
-// NOTE: If you add a instance method/property to this class that may conflict
-// with methods declared in protos, you need to update objective_helpers.cc.
-// The main cases are methods that take no arguments, or setFoo:/hasFoo: type
-// methods.
-
-/// The unknown fields for this message.
-///
-/// Only messages from proto files declared with "proto2" syntax support unknown
-/// fields. For "proto3" syntax, any unknown fields found while parsing are
-/// dropped.
+// If you add an instance method/property to this class that may conflict with
+// fields declared in protos, you need to update objective_helpers.cc. The main
+// cases are methods that take no arguments, or setFoo:/hasFoo: type methods.
+
+/**
+ * The set of unknown fields for this message.
+ *
+ * Only messages from proto files declared with "proto2" syntax support unknown
+ * fields. For "proto3" syntax, any unknown fields found while parsing are
+ * dropped.
+ **/
@property(nonatomic, copy, nullable) GPBUnknownFieldSet *unknownFields;
-/// Are all required fields set in the message and all embedded messages.
+/**
+ * Whether the message, along with all submessages, have the required fields
+ * set. This is only applicable for files declared with "proto2" syntax, as
+ * there are no required fields for "proto3" syntax.
+ **/
@property(nonatomic, readonly, getter=isInitialized) BOOL initialized;
-/// Returns an autoreleased instance.
+/**
+ * @return An autoreleased message with the default values set.
+ **/
+ (instancetype)message;
-/// Creates a new instance by parsing the data. This method should be sent to
-/// the generated message class that the data should be interpreted as. If
-/// there is an error the method returns nil and the error is returned in
-/// errorPtr (when provided).
-///
-/// @note In DEBUG builds, the parsed message is checked to be sure all required
-/// fields were provided, and the parse will fail if some are missing.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param data The data to parse.
-/// @param errorPtr An optional error pointer to fill in with a failure reason if
-/// the data can not be parsed.
-///
-/// @return A new instance of the class messaged.
+/**
+ * Creates a new instance by parsing the provided data. This method should be
+ * sent to the generated message class that the data should be interpreted as.
+ * If there is an error the method returns nil and the error is returned in
+ * errorPtr (when provided).
+ *
+ * @note In DEBUG builds, the parsed message is checked to be sure all required
+ * fields were provided, and the parse will fail if some are missing.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param data The data to parse.
+ * @param errorPtr An optional error pointer to fill in with a failure reason if
+ * the data can not be parsed.
+ *
+ * @return A new instance of the generated class.
+ **/
+ (nullable instancetype)parseFromData:(NSData *)data error:(NSError **)errorPtr;
-/// Creates a new instance by parsing the data. This method should be sent to
-/// the generated message class that the data should be interpreted as. If
-/// there is an error the method returns nil and the error is returned in
-/// errorPtr (when provided).
-///
-/// @note In DEBUG builds, the parsed message is checked to be sure all required
-/// fields were provided, and the parse will fail if some are missing.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param data The data to parse.
-/// @param extensionRegistry The extension registry to use to look up extensions.
-/// @param errorPtr An optional error pointer to fill in with a failure
-/// reason if the data can not be parsed.
-///
-/// @return A new instance of the class messaged.
+/**
+ * Creates a new instance by parsing the data. This method should be sent to
+ * the generated message class that the data should be interpreted as. If
+ * there is an error the method returns nil and the error is returned in
+ * errorPtr (when provided).
+ *
+ * @note In DEBUG builds, the parsed message is checked to be sure all required
+ * fields were provided, and the parse will fail if some are missing.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param data The data to parse.
+ * @param extensionRegistry The extension registry to use to look up extensions.
+ * @param errorPtr An optional error pointer to fill in with a failure
+ * reason if the data can not be parsed.
+ *
+ * @return A new instance of the generated class.
+ **/
+ (nullable instancetype)parseFromData:(NSData *)data
extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr;
-/// Creates a new instance by parsing the data from the given input stream. This
-/// method should be sent to the generated message class that the data should
-/// be interpreted as. If there is an error the method returns nil and the error
-/// is returned in errorPtr (when provided).
-///
-/// @note In DEBUG builds, the parsed message is checked to be sure all required
-/// fields were provided, and the parse will fail if some are missing.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param input The stream to read data from.
-/// @param extensionRegistry The extension registry to use to look up extensions.
-/// @param errorPtr An optional error pointer to fill in with a failure
-/// reason if the data can not be parsed.
-///
-/// @return A new instance of the class messaged.
+/**
+ * Creates a new instance by parsing the data from the given input stream. This
+ * method should be sent to the generated message class that the data should
+ * be interpreted as. If there is an error the method returns nil and the error
+ * is returned in errorPtr (when provided).
+ *
+ * @note In DEBUG builds, the parsed message is checked to be sure all required
+ * fields were provided, and the parse will fail if some are missing.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param input The stream to read data from.
+ * @param extensionRegistry The extension registry to use to look up extensions.
+ * @param errorPtr An optional error pointer to fill in with a failure
+ * reason if the data can not be parsed.
+ *
+ * @return A new instance of the generated class.
+ **/
+ (nullable instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input
extensionRegistry:
(nullable GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr;
-/// Creates a new instance by parsing the data from the given input stream. This
-/// method should be sent to the generated message class that the data should
-/// be interpreted as. If there is an error the method returns nil and the error
-/// is returned in errorPtr (when provided).
-///
-/// @note Unlike the parseFrom... methods, this never checks to see if all of
-/// the required fields are set. So this method can be used to reload
-/// messages that may not be complete.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param input The stream to read data from.
-/// @param extensionRegistry The extension registry to use to look up extensions.
-/// @param errorPtr An optional error pointer to fill in with a failure
-/// reason if the data can not be parsed.
-///
-/// @return A new instance of the class messaged.
+/**
+ * Creates a new instance by parsing the data from the given input stream. This
+ * method should be sent to the generated message class that the data should
+ * be interpreted as. If there is an error the method returns nil and the error
+ * is returned in errorPtr (when provided).
+ *
+ * @note Unlike the parseFrom... methods, this never checks to see if all of
+ * the required fields are set. So this method can be used to reload
+ * messages that may not be complete.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param input The stream to read data from.
+ * @param extensionRegistry The extension registry to use to look up extensions.
+ * @param errorPtr An optional error pointer to fill in with a failure
+ * reason if the data can not be parsed.
+ *
+ * @return A new instance of the generated class.
+ **/
+ (nullable instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input
extensionRegistry:
(nullable GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr;
-/// Initializes an instance by parsing the data. This method should be sent to
-/// the generated message class that the data should be interpreted as. If
-/// there is an error the method returns nil and the error is returned in
-/// errorPtr (when provided).
-///
-/// @note In DEBUG builds, the parsed message is checked to be sure all required
-/// fields were provided, and the parse will fail if some are missing.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param data The data to parse.
-/// @param errorPtr An optional error pointer to fill in with a failure reason if
-/// the data can not be parsed.
+/**
+ * Initializes an instance by parsing the data. This method should be sent to
+ * the generated message class that the data should be interpreted as. If
+ * there is an error the method returns nil and the error is returned in
+ * errorPtr (when provided).
+ *
+ * @note In DEBUG builds, the parsed message is checked to be sure all required
+ * fields were provided, and the parse will fail if some are missing.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param data The data to parse.
+ * @param errorPtr An optional error pointer to fill in with a failure reason if
+ * the data can not be parsed.
+ *
+ * @return An initialized instance of the generated class.
+ **/
- (nullable instancetype)initWithData:(NSData *)data error:(NSError **)errorPtr;
-/// Initializes an instance by parsing the data. This method should be sent to
-/// the generated message class that the data should be interpreted as. If
-/// there is an error the method returns nil and the error is returned in
-/// errorPtr (when provided).
-///
-/// @note In DEBUG builds, the parsed message is checked to be sure all required
-/// fields were provided, and the parse will fail if some are missing.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param data The data to parse.
-/// @param extensionRegistry The extension registry to use to look up extensions.
-/// @param errorPtr An optional error pointer to fill in with a failure
-/// reason if the data can not be parsed.
+/**
+ * Initializes an instance by parsing the data. This method should be sent to
+ * the generated message class that the data should be interpreted as. If
+ * there is an error the method returns nil and the error is returned in
+ * errorPtr (when provided).
+ *
+ * @note In DEBUG builds, the parsed message is checked to be sure all required
+ * fields were provided, and the parse will fail if some are missing.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param data The data to parse.
+ * @param extensionRegistry The extension registry to use to look up extensions.
+ * @param errorPtr An optional error pointer to fill in with a failure
+ * reason if the data can not be parsed.
+ *
+ * @return An initialized instance of the generated class.
+ **/
- (nullable instancetype)initWithData:(NSData *)data
extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr;
-/// Initializes an instance by parsing the data from the given input stream. This
-/// method should be sent to the generated message class that the data should
-/// be interpreted as. If there is an error the method returns nil and the error
-/// is returned in errorPtr (when provided).
-///
-/// @note Unlike the parseFrom... methods, this never checks to see if all of
-/// the required fields are set. So this method can be used to reload
-/// messages that may not be complete.
-///
-/// @note The errors returned are likely coming from the domain and codes listed
-/// at the top of this file and GPBCodedInputStream.h.
-///
-/// @param input The stream to read data from.
-/// @param extensionRegistry The extension registry to use to look up extensions.
-/// @param errorPtr An optional error pointer to fill in with a failure
-/// reason if the data can not be parsed.
+/**
+ * Initializes an instance by parsing the data from the given input stream. This
+ * method should be sent to the generated message class that the data should
+ * be interpreted as. If there is an error the method returns nil and the error
+ * is returned in errorPtr (when provided).
+ *
+ * @note Unlike the parseFrom... methods, this never checks to see if all of
+ * the required fields are set. So this method can be used to reload
+ * messages that may not be complete.
+ *
+ * @note The errors returned are likely coming from the domain and codes listed
+ * at the top of this file and GPBCodedInputStream.h.
+ *
+ * @param input The stream to read data from.
+ * @param extensionRegistry The extension registry to use to look up extensions.
+ * @param errorPtr An optional error pointer to fill in with a failure
+ * reason if the data can not be parsed.
+ *
+ * @return An initialized instance of the generated class.
+ **/
- (nullable instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input
extensionRegistry:
(nullable GPBExtensionRegistry *)extensionRegistry
error:(NSError **)errorPtr;
-/// Writes out the message to the given output stream.
+/**
+ * Parses the given data as this message's class, and merges those values into
+ * this message.
+ *
+ * @param data The binary representation of the message to merge.
+ * @param extensionRegistry The extension registry to use to look up extensions.
+ *
+ * @exception GPBCodedInputStreamException Exception thrown when parsing was
+ * unsuccessful.
+ **/
+- (void)mergeFromData:(NSData *)data
+ extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry;
+
+/**
+ * Merges the fields from another message (of the same type) into this
+ * message.
+ *
+ * @param other Message to merge into this message.
+ **/
+- (void)mergeFrom:(GPBMessage *)other;
+
+/**
+ * Writes out the message to the given coded output stream.
+ *
+ * @param output The coded output stream into which to write the message.
+ **/
- (void)writeToCodedOutputStream:(GPBCodedOutputStream *)output;
-/// Writes out the message to the given output stream.
+
+/**
+ * Writes out the message to the given output stream.
+ *
+ * @param output The output stream into which to write the message.
+ **/
- (void)writeToOutputStream:(NSOutputStream *)output;
-/// Writes out a varint for the message size followed by the the message to
-/// the given output stream.
+/**
+ * Writes out a varint for the message size followed by the the message to
+ * the given output stream.
+ *
+ * @param output The coded output stream into which to write the message.
+ **/
- (void)writeDelimitedToCodedOutputStream:(GPBCodedOutputStream *)output;
-/// Writes out a varint for the message size followed by the the message to
-/// the given output stream.
+
+/**
+ * Writes out a varint for the message size followed by the the message to
+ * the given output stream.
+ *
+ * @param output The output stream into which to write the message.
+ **/
- (void)writeDelimitedToOutputStream:(NSOutputStream *)output;
-/// Serializes the message to a @c NSData.
-///
-/// If there is an error while generating the data, nil is returned.
-///
-/// @note This value is not cached, so if you are using it repeatedly, cache
-/// it yourself.
-///
-/// @note In DEBUG ONLY, the message is also checked for all required field,
-/// if one is missing, nil will be returned.
+/**
+ * Serializes the message to an NSData.
+ *
+ * If there is an error while generating the data, nil is returned.
+ *
+ * @note This value is not cached, so if you are using it repeatedly, cache
+ * it yourself.
+ *
+ * @note In DEBUG ONLY, the message is also checked for all required field,
+ * if one is missing, nil will be returned.
+ *
+ * @return The binary representation of the message.
+ **/
- (nullable NSData *)data;
-/// Serializes a varint with the message size followed by the message data,
-/// returning that as a @c NSData.
-///
-/// @note This value is not cached, so if you are using it repeatedly, cache
-/// it yourself.
+/**
+ * Serializes a varint with the message size followed by the message data,
+ * returning that as an NSData.
+ *
+ * @note This value is not cached, so if you are using it repeatedly, it is
+ * recommended to keep a local copy.
+ *
+ * @return The binary representation of the size along with the message.
+ **/
- (NSData *)delimitedData;
-/// Calculates the size of the object if it were serialized.
-///
-/// This is not a cached value. If you are following a pattern like this:
-/// @code
-/// size_t size = [aMsg serializedSize];
-/// NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)];
-/// [foo writeSize:size];
-/// [foo appendData:[aMsg data]];
-/// @endcode
-/// you would be better doing:
-/// @code
-/// NSData *data = [aMsg data];
-/// NSUInteger size = [aMsg length];
-/// NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)];
-/// [foo writeSize:size];
-/// [foo appendData:data];
-/// @endcode
+/**
+ * Calculates the size of the object if it were serialized.
+ *
+ * This is not a cached value. If you are following a pattern like this:
+ *
+ * ```
+ * size_t size = [aMsg serializedSize];
+ * NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)];
+ * [foo writeSize:size];
+ * [foo appendData:[aMsg data]];
+ * ```
+ *
+ * you would be better doing:
+ *
+ * ```
+ * NSData *data = [aMsg data];
+ * NSUInteger size = [aMsg length];
+ * NSMutableData *foo = [NSMutableData dataWithCapacity:size + sizeof(size)];
+ * [foo writeSize:size];
+ * [foo appendData:data];
+ * ```
+ *
+ * @return The size of the message in it's binary representation.
+ **/
- (size_t)serializedSize;
-/// Return the descriptor for the message class.
+/**
+ * @return The descriptor for the message class.
+ **/
+ (GPBDescriptor *)descriptor;
-/// Return the descriptor for the message.
+
+/**
+ * Return the descriptor for the message.
+ **/
- (GPBDescriptor *)descriptor;
-/// Returns an array with the currently set GPBExtensionDescriptors.
+/**
+ * @return An array with the extension descriptors that are currently set on the
+ * message.
+ **/
- (NSArray *)extensionsCurrentlySet;
-/// Test to see if the given extension is set on the message.
+/**
+ * Checks whether there is an extension set on the message which matches the
+ * given extension descriptor.
+ *
+ * @param extension Extension descriptor to check if it's set on the message.
+ *
+ * @return Whether the extension is currently set on the message.
+ **/
- (BOOL)hasExtension:(GPBExtensionDescriptor *)extension;
-/// Fetches the given extension's value for this message.
-///
-/// Extensions use boxed values (NSNumbers) for PODs and NSMutableArrays for
-/// repeated fields. If the extension is a Message one will be auto created for you
-/// and returned similar to fields.
+/*
+ * Fetches the given extension's value for this message.
+ *
+ * Extensions use boxed values (NSNumbers) for PODs and NSMutableArrays for
+ * repeated fields. If the extension is a Message one will be auto created for
+ * you and returned similar to fields.
+ *
+ * @param extension The extension descriptor of the extension to fetch.
+ *
+ * @return The extension matching the given descriptor, or nil if none found.
+ **/
- (nullable id)getExtension:(GPBExtensionDescriptor *)extension;
-/// Sets the given extension's value for this message. This is only for single
-/// field extensions (i.e. - not repeated fields).
-///
-/// Extensions use boxed values (@c NSNumbers).
-- (void)setExtension:(GPBExtensionDescriptor *)extension value:(nullable id)value;
-
-/// Adds the given value to the extension for this message. This is only for
-/// repeated field extensions. If the field is a repeated POD type the @c value
-/// is a @c NSNumber.
+/**
+ * Sets the given extension's value for this message. This only applies for
+ * single field extensions (i.e. - not repeated fields).
+ *
+ * Extensions use boxed values (NSNumbers).
+ *
+ * @param extension The extension descriptor under which to set the value.
+ * @param value The value to be set as the extension.
+ **/
+- (void)setExtension:(GPBExtensionDescriptor *)extension
+ value:(nullable id)value;
+
+/**
+ * Adds the given value to the extension for this message. This only applies
+ * to repeated field extensions. If the field is a repeated POD type, the value
+ * should be an NSNumber.
+ *
+ * @param extension The extension descriptor under which to add the value.
+ * @param value The value to be added to the repeated extension.
+ **/
- (void)addExtension:(GPBExtensionDescriptor *)extension value:(id)value;
-/// Replaces the given value at an index for the extension on this message. This
-/// is only for repeated field extensions. If the field is a repeated POD type
-/// the @c value is a @c NSNumber.
+/**
+ * Replaces the value at the given index with the given value for the extension
+ * on this message. This only applies to repeated field extensions. If the field
+ * is a repeated POD type, the value is should be an NSNumber.
+ *
+ * @param extension The extension descriptor under which to replace the value.
+ * @param index The index of the extension to be replaced.
+ * @param value The value to be replaced in the repeated extension.
+ **/
- (void)setExtension:(GPBExtensionDescriptor *)extension
index:(NSUInteger)index
value:(id)value;
-/// Clears the given extension for this message.
+/**
+ * Clears the given extension for this message.
+ *
+ * @param extension The extension descriptor to be cleared from this message.
+ **/
- (void)clearExtension:(GPBExtensionDescriptor *)extension;
-/// Resets all of the fields of this message to their default values.
+/**
+ * Resets all of the fields of this message to their default values.
+ **/
- (void)clear;
-/// Parses a message of this type from the input and merges it with this
-/// message.
-///
-/// @note This will throw if there is an error parsing the data.
-- (void)mergeFromData:(NSData *)data
- extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry;
-
-/// Merges the fields from another message (of the same type) into this
-/// message.
-- (void)mergeFrom:(GPBMessage *)other;
-
@end
NS_ASSUME_NONNULL_END
diff --git a/objectivec/GPBRootObject.h b/objectivec/GPBRootObject.h
index c05b5c62..d2e2aebf 100644
--- a/objectivec/GPBRootObject.h
+++ b/objectivec/GPBRootObject.h
@@ -34,12 +34,17 @@
NS_ASSUME_NONNULL_BEGIN
-/// Every generated proto file defines a local "Root" class that exposes a
-/// @c GPBExtensionRegistry for all the extensions defined by that file and
-/// the files it depends on.
+/**
+ * Every generated proto file defines a local "Root" class that exposes a
+ * GPBExtensionRegistry for all the extensions defined by that file and
+ * the files it depends on.
+ **/
@interface GPBRootObject : NSObject
-/// An extension registry for the given file and all the files it depends on.
+/**
+ * @return An extension registry for the given file and all the files it depends
+ * on.
+ **/
+ (GPBExtensionRegistry *)extensionRegistry;
@end
diff --git a/objectivec/GPBRuntimeTypes.h b/objectivec/GPBRuntimeTypes.h
index 0a38b110..4d552060 100644
--- a/objectivec/GPBRuntimeTypes.h
+++ b/objectivec/GPBRuntimeTypes.h
@@ -36,21 +36,28 @@
@class GPBMessage;
@class GPBInt32Array;
-// Function used to verify that a given value can be represented by an
-// enum type.
+/**
+ * Verifies that a given value can be represented by an enum type.
+ * */
typedef BOOL (*GPBEnumValidationFunc)(int32_t);
-// Function used to fetch an EnumDescriptor.
+/**
+ * Fetches an EnumDescriptor.
+ * */
typedef GPBEnumDescriptor *(*GPBEnumDescriptorFunc)(void);
-// Magic values used for when an the at runtime to indicate an enum value
-// that wasn't know at compile time.
+/**
+ * Magic value used at runtime to indicate an enum value that wasn't know at
+ * compile time.
+ * */
enum {
kGPBUnrecognizedEnumeratorValue = (int32_t)0xFBADBEEF,
};
-// A union for storing all possible Protobuf values.
-// Note that owner is responsible for memory management of object types.
+/**
+ * A union for storing all possible Protobuf values. Note that owner is
+ * responsible for memory management of object types.
+ * */
typedef union {
BOOL valueBool;
int32_t valueInt32;
@@ -65,38 +72,73 @@ typedef union {
int32_t valueEnum;
} GPBGenericValue;
-// Do not change the order of this enum (or add things to it) without thinking
-// about it very carefully. There are several things that depend on the order.
+/**
+ * Enum listing the possible data types that a field can contain.
+ *
+ * @note Do not change the order of this enum (or add things to it) without
+ * thinking about it very carefully. There are several things that depend
+ * on the order.
+ * */
typedef NS_ENUM(uint8_t, GPBDataType) {
+ /** Field contains boolean value(s). */
GPBDataTypeBool = 0,
+ /** Field contains unsigned 4 byte value(s). */
GPBDataTypeFixed32,
+ /** Field contains signed 4 byte value(s). */
GPBDataTypeSFixed32,
+ /** Field contains float value(s). */
GPBDataTypeFloat,
+ /** Field contains unsigned 8 byte value(s). */
GPBDataTypeFixed64,
+ /** Field contains signed 8 byte value(s). */
GPBDataTypeSFixed64,
+ /** Field contains double value(s). */
GPBDataTypeDouble,
+ /**
+ * Field contains variable length value(s). Inefficient for encoding negative
+ * numbers – if your field is likely to have negative values, use
+ * GPBDataTypeSInt32 instead.
+ **/
GPBDataTypeInt32,
+ /**
+ * Field contains variable length value(s). Inefficient for encoding negative
+ * numbers – if your field is likely to have negative values, use
+ * GPBDataTypeSInt64 instead.
+ **/
GPBDataTypeInt64,
+ /** Field contains signed variable length integer value(s). */
GPBDataTypeSInt32,
+ /** Field contains signed variable length integer value(s). */
GPBDataTypeSInt64,
+ /** Field contains unsigned variable length integer value(s). */
GPBDataTypeUInt32,
+ /** Field contains unsigned variable length integer value(s). */
GPBDataTypeUInt64,
+ /** Field contains an arbitrary sequence of bytes. */
GPBDataTypeBytes,
+ /** Field contains UTF-8 encoded or 7-bit ASCII text. */
GPBDataTypeString,
+ /** Field contains message type(s). */
GPBDataTypeMessage,
+ /** Field contains message type(s). */
GPBDataTypeGroup,
+ /** Field contains enum value(s). */
GPBDataTypeEnum,
};
enum {
- // A count of the number of types in GPBDataType. Separated out from the
- // GPBDataType enum to avoid warnings regarding not handling
- // GPBDataType_Count in switch statements.
+ /**
+ * A count of the number of types in GPBDataType. Separated out from the
+ * GPBDataType enum to avoid warnings regarding not handling GPBDataType_Count
+ * in switch statements.
+ **/
GPBDataType_Count = GPBDataTypeEnum + 1
};
-// An extension range.
+/** An extension range. */
typedef struct GPBExtensionRange {
- uint32_t start; // inclusive
- uint32_t end; // exclusive
+ /** Inclusive. */
+ uint32_t start;
+ /** Exclusive. */
+ uint32_t end;
} GPBExtensionRange;
diff --git a/objectivec/GPBUnknownField.h b/objectivec/GPBUnknownField.h
index 0f301e47..a135cc20 100644
--- a/objectivec/GPBUnknownField.h
+++ b/objectivec/GPBUnknownField.h
@@ -36,52 +36,59 @@
@class GPBUnknownFieldSet;
NS_ASSUME_NONNULL_BEGIN
-
-/// Store an unknown field. These are used in conjunction with @c GPBUnknownFieldSet
+/**
+ * Store an unknown field. These are used in conjunction with
+ * GPBUnknownFieldSet.
+ **/
@interface GPBUnknownField : NSObject<NSCopying>
-/// The field number the data is stored under.
+/** The field number the data is stored under. */
@property(nonatomic, readonly, assign) int32_t number;
-/// An array of varint values for this field.
+/** An array of varint values for this field. */
@property(nonatomic, readonly, strong) GPBUInt64Array *varintList;
-/// An array of fixed32 values for this field.
+/** An array of fixed32 values for this field. */
@property(nonatomic, readonly, strong) GPBUInt32Array *fixed32List;
-/// An array of fixed64 values for this field.
+/** An array of fixed64 values for this field. */
@property(nonatomic, readonly, strong) GPBUInt64Array *fixed64List;
-/// An array of data values for this field.
+/** An array of data values for this field. */
@property(nonatomic, readonly, strong) NSArray<NSData*> *lengthDelimitedList;
-/// An array of groups of values for this field.
+/** An array of groups of values for this field. */
@property(nonatomic, readonly, strong) NSArray<GPBUnknownFieldSet*> *groupList;
-
-/// Add a value to the varintList.
-///
-/// @param value The value to add.
+/**
+ * Add a value to the varintList.
+ *
+ * @param value The value to add.
+ **/
- (void)addVarint:(uint64_t)value;
-
-/// Add a value to the fixed32List.
-///
-/// @param value The value to add.
+/**
+ * Add a value to the fixed32List.
+ *
+ * @param value The value to add.
+ **/
- (void)addFixed32:(uint32_t)value;
-
-/// Add a value to the fixed64List.
-///
-/// @param value The value to add.
+/**
+ * Add a value to the fixed64List.
+ *
+ * @param value The value to add.
+ **/
- (void)addFixed64:(uint64_t)value;
-
-/// Add a value to the lengthDelimitedList.
-///
-/// @param value The value to add.
+/**
+ * Add a value to the lengthDelimitedList.
+ *
+ * @param value The value to add.
+ **/
- (void)addLengthDelimited:(NSData *)value;
-
-/// Add a value to the groupList.
-///
-/// @param value The value to add.
+/**
+ * Add a value to the groupList.
+ *
+ * @param value The value to add.
+ **/
- (void)addGroup:(GPBUnknownFieldSet *)value;
@end
diff --git a/objectivec/GPBUnknownFieldSet.h b/objectivec/GPBUnknownFieldSet.h
index cf612993..1b5f24f3 100644
--- a/objectivec/GPBUnknownFieldSet.h
+++ b/objectivec/GPBUnknownFieldSet.h
@@ -34,31 +34,48 @@
NS_ASSUME_NONNULL_BEGIN
-/// A collection of unknown fields.
+/**
+ * A collection of unknown fields. Fields parsed from the binary representation
+ * of a message that are unknown end up in an instance of this set. This only
+ * applies for files declared with the "proto2" syntax. Files declared with the
+ * "proto3" syntax discard the unknown values.
+ **/
@interface GPBUnknownFieldSet : NSObject<NSCopying>
-/// Tests to see if the given field number has a value.
-///
-/// @param number The field number to check.
-///
-/// @return YES if there is an unknown field for the given field number.
+/**
+ * Tests to see if the given field number has a value.
+ *
+ * @param number The field number to check.
+ *
+ * @return YES if there is an unknown field for the given field number.
+ **/
- (BOOL)hasField:(int32_t)number;
-/// Fetches the @c GPBUnknownField for the given field number.
-///
-/// @param number The field number to look up.
-///
-/// @return The @c GPBUnknownField or nil.
+/**
+ * Fetches the GPBUnknownField for the given field number.
+ *
+ * @param number The field number to look up.
+ *
+ * @return The GPBUnknownField or nil if none found.
+ **/
- (nullable GPBUnknownField *)getField:(int32_t)number;
-/// Returns the number of fields in this set.
+/**
+ * @return The number of fields in this set.
+ **/
- (NSUInteger)countOfFields;
-/// Adds the given field to the set.
+/**
+ * Adds the given field to the set.
+ *
+ * @param field The field to add to the set.
+ **/
- (void)addField:(GPBUnknownField *)field;
-/// Returns an NSArray of the @c GPBUnknownFields sorted by the field numbers.
-- (NSArray<GPBUnknownField*> *)sortedFields;
+/**
+ * @return An array of the GPBUnknownFields sorted by the field numbers.
+ **/
+- (NSArray<GPBUnknownField *> *)sortedFields;
@end
diff --git a/objectivec/GPBUnknownFieldSet.m b/objectivec/GPBUnknownFieldSet.m
index 9ba1d65c..a7335f05 100644
--- a/objectivec/GPBUnknownFieldSet.m
+++ b/objectivec/GPBUnknownFieldSet.m
@@ -36,39 +36,6 @@
#import "GPBUtilities.h"
#import "GPBWireFormat.h"
-#pragma mark CFDictionaryKeyCallBacks
-
-// We use a custom dictionary here because our keys are numbers and
-// conversion back and forth from NSNumber was costing us performance.
-// If/when we move to C++ this could be done using a std::map and some
-// careful retain/release calls.
-
-static const void *GPBUnknownFieldSetKeyRetain(CFAllocatorRef allocator,
- const void *value) {
-#pragma unused(allocator)
- return value;
-}
-
-static void GPBUnknownFieldSetKeyRelease(CFAllocatorRef allocator,
- const void *value) {
-#pragma unused(allocator)
-#pragma unused(value)
-}
-
-static CFStringRef GPBUnknownFieldSetCopyKeyDescription(const void *value) {
- return CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%d"),
- (int)value);
-}
-
-static Boolean GPBUnknownFieldSetKeyEqual(const void *value1,
- const void *value2) {
- return value1 == value2;
-}
-
-static CFHashCode GPBUnknownFieldSetKeyHash(const void *value) {
- return (CFHashCode)value;
-}
-
#pragma mark Helpers
static void checkNumber(int32_t number) {
@@ -291,13 +258,9 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key,
int32_t number = [field number];
checkNumber(number);
if (!fields_) {
- CFDictionaryKeyCallBacks keyCallBacks = {
- // See description above for reason for using custom dictionary.
- 0, GPBUnknownFieldSetKeyRetain, GPBUnknownFieldSetKeyRelease,
- GPBUnknownFieldSetCopyKeyDescription, GPBUnknownFieldSetKeyEqual,
- GPBUnknownFieldSetKeyHash,
- };
- fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks,
+ // Use a custom dictionary here because the keys are numbers and conversion
+ // back and forth from NSNumber isn't worth the cost.
+ fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL,
&kCFTypeDictionaryValueCallBacks);
}
ssize_t key = number;
diff --git a/objectivec/GPBUtilities.h b/objectivec/GPBUtilities.h
index b7209324..52e7d2e0 100644
--- a/objectivec/GPBUtilities.h
+++ b/objectivec/GPBUtilities.h
@@ -38,34 +38,58 @@ CF_EXTERN_C_BEGIN
NS_ASSUME_NONNULL_BEGIN
-/// Generates a string that should be a valid "Text Format" for the C++ version
-/// of Protocol Buffers.
-///
-/// @param message The message to generate from.
-/// @param lineIndent A string to use as the prefix for all lines generated. Can
-/// be nil if no extra indent is needed.
-///
-/// @return A @c NSString with the Text Format of the message.
+/**
+ * Generates a string that should be a valid "TextFormat" for the C++ version
+ * of Protocol Buffers.
+ *
+ * @param message The message to generate from.
+ * @param lineIndent A string to use as the prefix for all lines generated. Can
+ * be nil if no extra indent is needed.
+ *
+ * @return An NSString with the TextFormat of the message.
+ **/
NSString *GPBTextFormatForMessage(GPBMessage *message,
NSString * __nullable lineIndent);
-/// Generates a string that should be a valid "Text Format" for the C++ version
-/// of Protocol Buffers.
-///
-/// @param unknownSet The unknown field set to generate from.
-/// @param lineIndent A string to use as the prefix for all lines generated. Can
-/// be nil if no extra indent is needed.
-///
-/// @return A @c NSString with the Text Format of the unknown field set.
+/**
+ * Generates a string that should be a valid "TextFormat" for the C++ version
+ * of Protocol Buffers.
+ *
+ * @param unknownSet The unknown field set to generate from.
+ * @param lineIndent A string to use as the prefix for all lines generated. Can
+ * be nil if no extra indent is needed.
+ *
+ * @return An NSString with the TextFormat of the unknown field set.
+ **/
NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet * __nullable unknownSet,
NSString * __nullable lineIndent);
-/// Test if the given field is set on a message.
+/**
+ * Checks if the given field number is set on a message.
+ *
+ * @param self The message to check.
+ * @param fieldNumber The field number to check.
+ *
+ * @return YES if the field number is set on the given message.
+ **/
BOOL GPBMessageHasFieldNumberSet(GPBMessage *self, uint32_t fieldNumber);
-/// Test if the given field is set on a message.
+
+/**
+ * Checks if the given field is set on a message.
+ *
+ * @param self The message to check.
+ * @param field The field to check.
+ *
+ * @return YES if the field is set on the given message.
+ **/
BOOL GPBMessageHasFieldSet(GPBMessage *self, GPBFieldDescriptor *field);
-/// Clear the given field of a message.
+/**
+ * Clears the given field for the given message.
+ *
+ * @param self The message for which to clear the field.
+ * @param field The field to clear.
+ **/
void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field);
//%PDDM-EXPAND GPB_ACCESSORS()
@@ -73,112 +97,299 @@ void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field);
//
-// Get/Set the given field of a message.
+// Get/Set a given field from/to a message.
//
// Single Fields
-/// Gets the value of a bytes field.
+/**
+ * Gets the value of a bytes field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
NSData *GPBGetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a bytes field.
+
+/**
+ * Sets the value of a bytes field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageBytesField(GPBMessage *self, GPBFieldDescriptor *field, NSData *value);
-/// Gets the value of a string field.
+/**
+ * Gets the value of a string field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
NSString *GPBGetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a string field.
+
+/**
+ * Sets the value of a string field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageStringField(GPBMessage *self, GPBFieldDescriptor *field, NSString *value);
-/// Gets the value of a message field.
+/**
+ * Gets the value of a message field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
GPBMessage *GPBGetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a message field.
+
+/**
+ * Sets the value of a message field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageMessageField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value);
-/// Gets the value of a group field.
+/**
+ * Gets the value of a group field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
GPBMessage *GPBGetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a group field.
+
+/**
+ * Sets the value of a group field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageGroupField(GPBMessage *self, GPBFieldDescriptor *field, GPBMessage *value);
-/// Gets the value of a bool field.
+/**
+ * Gets the value of a bool field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
BOOL GPBGetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a bool field.
+
+/**
+ * Sets the value of a bool field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value);
-/// Gets the value of an int32 field.
+/**
+ * Gets the value of an int32 field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
int32_t GPBGetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of an int32 field.
+
+/**
+ * Sets the value of an int32 field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field, int32_t value);
-/// Gets the value of an uint32 field.
+/**
+ * Gets the value of an uint32 field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
uint32_t GPBGetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of an uint32 field.
+
+/**
+ * Sets the value of an uint32 field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value);
-/// Gets the value of an int64 field.
+/**
+ * Gets the value of an int64 field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
int64_t GPBGetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of an int64 field.
+
+/**
+ * Sets the value of an int64 field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field, int64_t value);
-/// Gets the value of an uint64 field.
+/**
+ * Gets the value of an uint64 field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
uint64_t GPBGetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of an uint64 field.
+
+/**
+ * Sets the value of an uint64 field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value);
-/// Gets the value of a float field.
+/**
+ * Gets the value of a float field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
float GPBGetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a float field.
+
+/**
+ * Sets the value of a float field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field, float value);
-/// Gets the value of a double field.
+/**
+ * Gets the value of a double field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ **/
double GPBGetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a double field.
+
+/**
+ * Sets the value of a double field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The to set in the field.
+ **/
void GPBSetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field, double value);
-/// Get the given enum field of a message. For proto3, if the value isn't a
-/// member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned.
-/// GPBGetMessageRawEnumField will bypass the check and return whatever value
-/// was set.
+/**
+ * Gets the given enum field of a message. For proto3, if the value isn't a
+ * member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned.
+ * GPBGetMessageRawEnumField will bypass the check and return whatever value
+ * was set.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ *
+ * @return The enum value for the given field.
+ **/
int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Set the given enum field of a message. You can only set values that are
-/// members of the enum.
-void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value);
-/// Get the given enum field of a message. No check is done to ensure the value
-/// was defined in the enum.
+
+/**
+ * Set the given enum field of a message. You can only set values that are
+ * members of the enum.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The enum value to set in the field.
+ **/
+void GPBSetMessageEnumField(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value);
+
+/**
+ * Get the given enum field of a message. No check is done to ensure the value
+ * was defined in the enum.
+ *
+ * @param self The message from which to get the field.
+ * @param field The field to get.
+ *
+ * @return The raw enum value for the given field.
+ **/
int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Set the given enum field of a message. You can set the value to anything,
-/// even a value that is not a member of the enum.
-void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value);
+
+/**
+ * Set the given enum field of a message. You can set the value to anything,
+ * even a value that is not a member of the enum.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param value The raw enum value to set in the field.
+ **/
+void GPBSetMessageRawEnumField(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ int32_t value);
// Repeated Fields
-/// Gets the value of a repeated field.
-///
-/// The result will be @c GPB*Array or @c NSMutableArray based on the
-/// field's type.
+/**
+ * Gets the value of a repeated field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The repeated field to get.
+ *
+ * @return A GPB*Array or an NSMutableArray based on the field's type.
+ **/
id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a repeated field.
-///
-/// The value should be @c GPB*Array or @c NSMutableArray based on the
-/// field's type.
-void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array);
+
+/**
+ * Sets the value of a repeated field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param array A GPB*Array or NSMutableArray based on the field's type.
+ **/
+void GPBSetMessageRepeatedField(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ id array);
// Map Fields
-/// Gets the value of a map<> field.
-///
-/// The result will be @c GPB*Dictionary or @c NSMutableDictionary based on
-/// the field's type.
+/**
+ * Gets the value of a map<> field.
+ *
+ * @param self The message from which to get the field.
+ * @param field The repeated field to get.
+ *
+ * @return A GPB*Dictionary or NSMutableDictionary based on the field's type.
+ **/
id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field);
-/// Sets the value of a map<> field.
-///
-/// The object should be @c GPB*Dictionary or @c NSMutableDictionary based
-/// on the field's type.
-void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary);
+
+/**
+ * Sets the value of a map<> field.
+ *
+ * @param self The message into which to set the field.
+ * @param field The field to set.
+ * @param dictionary A GPB*Dictionary or NSMutableDictionary based on the
+ * field's type.
+ **/
+void GPBSetMessageMapField(GPBMessage *self,
+ GPBFieldDescriptor *field,
+ id dictionary);
//%PDDM-EXPAND-END GPB_ACCESSORS()
-// Returns an empty NSData to assign to byte fields when you wish
-// to assign them to empty. Prevents allocating a lot of little [NSData data]
-// objects.
+/**
+ * Returns an empty NSData to assign to byte fields when you wish to assign them
+ * to empty. Prevents allocating a lot of little [NSData data] objects.
+ **/
NSData *GPBEmptyNSData(void) __attribute__((pure));
NS_ASSUME_NONNULL_END
@@ -189,7 +400,7 @@ CF_EXTERN_C_END
//%PDDM-DEFINE GPB_ACCESSORS()
//%
//%//
-//%// Get/Set the given field of a message.
+//%// Get/Set a given field from/to a message.
//%//
//%
//%// Single Fields
@@ -205,53 +416,119 @@ CF_EXTERN_C_END
//%GPB_ACCESSOR_SINGLE(UInt64, uint64_t, n)
//%GPB_ACCESSOR_SINGLE(Float, float, )
//%GPB_ACCESSOR_SINGLE(Double, double, )
-//%/// Get the given enum field of a message. For proto3, if the value isn't a
-//%/// member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned.
-//%/// GPBGetMessageRawEnumField will bypass the check and return whatever value
-//%/// was set.
+//%/**
+//% * Gets the given enum field of a message. For proto3, if the value isn't a
+//% * member of the enum, @c kGPBUnrecognizedEnumeratorValue will be returned.
+//% * GPBGetMessageRawEnumField will bypass the check and return whatever value
+//% * was set.
+//% *
+//% * @param self The message from which to get the field.
+//% * @param field The field to get.
+//% *
+//% * @return The enum value for the given field.
+//% **/
//%int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field);
-//%/// Set the given enum field of a message. You can only set values that are
-//%/// members of the enum.
-//%void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value);
-//%/// Get the given enum field of a message. No check is done to ensure the value
-//%/// was defined in the enum.
+//%
+//%/**
+//% * Set the given enum field of a message. You can only set values that are
+//% * members of the enum.
+//% *
+//% * @param self The message into which to set the field.
+//% * @param field The field to set.
+//% * @param value The enum value to set in the field.
+//% **/
+//%void GPBSetMessageEnumField(GPBMessage *self,
+//% GPBFieldDescriptor *field,
+//% int32_t value);
+//%
+//%/**
+//% * Get the given enum field of a message. No check is done to ensure the value
+//% * was defined in the enum.
+//% *
+//% * @param self The message from which to get the field.
+//% * @param field The field to get.
+//% *
+//% * @return The raw enum value for the given field.
+//% **/
//%int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field);
-//%/// Set the given enum field of a message. You can set the value to anything,
-//%/// even a value that is not a member of the enum.
-//%void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value);
+//%
+//%/**
+//% * Set the given enum field of a message. You can set the value to anything,
+//% * even a value that is not a member of the enum.
+//% *
+//% * @param self The message into which to set the field.
+//% * @param field The field to set.
+//% * @param value The raw enum value to set in the field.
+//% **/
+//%void GPBSetMessageRawEnumField(GPBMessage *self,
+//% GPBFieldDescriptor *field,
+//% int32_t value);
//%
//%// Repeated Fields
//%
-//%/// Gets the value of a repeated field.
-//%///
-//%/// The result will be @c GPB*Array or @c NSMutableArray based on the
-//%/// field's type.
+//%/**
+//% * Gets the value of a repeated field.
+//% *
+//% * @param self The message from which to get the field.
+//% * @param field The repeated field to get.
+//% *
+//% * @return A GPB*Array or an NSMutableArray based on the field's type.
+//% **/
//%id GPBGetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field);
-//%/// Sets the value of a repeated field.
-//%///
-//%/// The value should be @c GPB*Array or @c NSMutableArray based on the
-//%/// field's type.
-//%void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id array);
+//%
+//%/**
+//% * Sets the value of a repeated field.
+//% *
+//% * @param self The message into which to set the field.
+//% * @param field The field to set.
+//% * @param array A GPB*Array or NSMutableArray based on the field's type.
+//% **/
+//%void GPBSetMessageRepeatedField(GPBMessage *self,
+//% GPBFieldDescriptor *field,
+//% id array);
//%
//%// Map Fields
//%
-//%/// Gets the value of a map<> field.
-//%///
-//%/// The result will be @c GPB*Dictionary or @c NSMutableDictionary based on
-//%/// the field's type.
+//%/**
+//% * Gets the value of a map<> field.
+//% *
+//% * @param self The message from which to get the field.
+//% * @param field The repeated field to get.
+//% *
+//% * @return A GPB*Dictionary or NSMutableDictionary based on the field's type.
+//% **/
//%id GPBGetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field);
-//%/// Sets the value of a map<> field.
-//%///
-//%/// The object should be @c GPB*Dictionary or @c NSMutableDictionary based
-//%/// on the field's type.
-//%void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary);
+//%
+//%/**
+//% * Sets the value of a map<> field.
+//% *
+//% * @param self The message into which to set the field.
+//% * @param field The field to set.
+//% * @param dictionary A GPB*Dictionary or NSMutableDictionary based on the
+//% * field's type.
+//% **/
+//%void GPBSetMessageMapField(GPBMessage *self,
+//% GPBFieldDescriptor *field,
+//% id dictionary);
//%
//%PDDM-DEFINE GPB_ACCESSOR_SINGLE(NAME, TYPE, AN)
//%GPB_ACCESSOR_SINGLE_FULL(NAME, TYPE, AN, )
//%PDDM-DEFINE GPB_ACCESSOR_SINGLE_FULL(NAME, TYPE, AN, TisP)
-//%/// Gets the value of a##AN NAME$L field.
+//%/**
+//% * Gets the value of a##AN NAME$L field.
+//% *
+//% * @param self The message from which to get the field.
+//% * @param field The field to get.
+//% **/
//%TYPE TisP##GPBGetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field);
-//%/// Sets the value of a##AN NAME$L field.
+//%
+//%/**
+//% * Sets the value of a##AN NAME$L field.
+//% *
+//% * @param self The message into which to set the field.
+//% * @param field The field to set.
+//% * @param value The to set in the field.
+//% **/
//%void GPBSetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field, TYPE TisP##value);
//%
diff --git a/objectivec/GPBUtilities.m b/objectivec/GPBUtilities.m
index ee84fb45..d4538598 100644
--- a/objectivec/GPBUtilities.m
+++ b/objectivec/GPBUtilities.m
@@ -58,8 +58,50 @@ NSData *GPBEmptyNSData(void) {
return defaultNSData;
}
+// -- About Version Checks --
+// There's actually 3 places these checks all come into play:
+// 1. When the generated source is compile into .o files, the header check
+// happens. This is checking the protoc used matches the library being used
+// when making the .o.
+// 2. Every place a generated proto header is included in a developer's code,
+// the header check comes into play again. But this time it is checking that
+// the current library headers being used still support/match the ones for
+// the generated code.
+// 3. At runtime the final check here (GPBCheckRuntimeVersionsInternal), is
+// called from the generated code passing in values captured when the
+// generated code's .o was made. This checks that at runtime the generated
+// code and runtime library match.
+
+void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion) {
+ // NOTE: This is passing the value captured in the compiled code to check
+ // against the values captured when the runtime support was compiled. This
+ // ensures the library code isn't in a different framework/library that
+ // was generated with a non matching version.
+ if (GOOGLE_PROTOBUF_OBJC_VERSION < objcRuntimeVersion) {
+ // Library is too old for headers.
+ [NSException raise:NSInternalInconsistencyException
+ format:@"Linked to ProtocolBuffer runtime version %d,"
+ @" but code compiled needing atleast %d!",
+ GOOGLE_PROTOBUF_OBJC_VERSION, objcRuntimeVersion];
+ }
+ if (objcRuntimeVersion < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) {
+ // Headers are too old for library.
+ [NSException raise:NSInternalInconsistencyException
+ format:@"Proto generation source compiled against runtime"
+ @" version %d, but this version of the runtime only"
+ @" supports back to %d!",
+ objcRuntimeVersion,
+ GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION];
+ }
+}
+
+// This api is no longer used for version checks. 30001 is the last version
+// using this old versioning model. When that support is removed, this function
+// can be removed (along with the declaration in GPBUtilities_PackagePrivate.h).
void GPBCheckRuntimeVersionInternal(int32_t version) {
- if (version != GOOGLE_PROTOBUF_OBJC_GEN_VERSION) {
+ GPBInternalCompileAssert(GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION == 30001,
+ time_to_remove_this_old_version_shim);
+ if (version != GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION) {
[NSException raise:NSInternalInconsistencyException
format:@"Linked to ProtocolBuffer runtime version %d,"
@" but code compiled with version %d!",
@@ -218,9 +260,10 @@ void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof,
//% TYPE *typePtr = (TYPE *)&storage[field->description_->offset];
//% *typePtr = value;
//% // proto2: any value counts as having been set; proto3, it
-//% // has to be a non zero value.
-//% BOOL hasValue =
-//% (syntax == GPBFileSyntaxProto2) || (value != (TYPE)0);
+//% // has to be a non zero value or be in a oneof.
+//% BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+//% || (value != (TYPE)0)
+//% || (field->containingOneof_ != NULL));
//% GPBSetHasIvarField(self, field, hasValue);
//% GPBBecomeVisibleToAutocreator(self);
//%}
@@ -337,8 +380,19 @@ void GPBSetRetainedObjectIvarWithFieldInternal(GPBMessage *self,
// zero, they are being cleared.
if ((syntax == GPBFileSyntaxProto3) && !fieldIsMessage &&
([value length] == 0)) {
- setHasValue = NO;
- value = nil;
+ // Except, if the field was in a oneof, then it still gets recorded as
+ // having been set so the state of the oneof can be serialized back out.
+ if (!oneof) {
+ setHasValue = NO;
+ }
+ if (setHasValue) {
+ NSCAssert(value != nil, @"Should never be setting has for nil");
+ } else {
+ // The value passed in was retained, it must be released since we
+ // aren't saving anything in the field.
+ [value release];
+ value = nil;
+ }
}
GPBSetHasIvarField(self, field, setHasValue);
}
@@ -524,9 +578,10 @@ void GPBSetBoolIvarWithFieldInternal(GPBMessage *self,
GPBSetHasIvar(self, (int32_t)(fieldDesc->offset), fieldDesc->number, value);
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (BOOL)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (BOOL)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -573,9 +628,10 @@ void GPBSetInt32IvarWithFieldInternal(GPBMessage *self,
int32_t *typePtr = (int32_t *)&storage[field->description_->offset];
*typePtr = value;
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (int32_t)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (int32_t)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -622,9 +678,10 @@ void GPBSetUInt32IvarWithFieldInternal(GPBMessage *self,
uint32_t *typePtr = (uint32_t *)&storage[field->description_->offset];
*typePtr = value;
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (uint32_t)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (uint32_t)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -671,9 +728,10 @@ void GPBSetInt64IvarWithFieldInternal(GPBMessage *self,
int64_t *typePtr = (int64_t *)&storage[field->description_->offset];
*typePtr = value;
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (int64_t)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (int64_t)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -720,9 +778,10 @@ void GPBSetUInt64IvarWithFieldInternal(GPBMessage *self,
uint64_t *typePtr = (uint64_t *)&storage[field->description_->offset];
*typePtr = value;
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (uint64_t)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (uint64_t)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -769,9 +828,10 @@ void GPBSetFloatIvarWithFieldInternal(GPBMessage *self,
float *typePtr = (float *)&storage[field->description_->offset];
*typePtr = value;
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (float)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (float)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -818,9 +878,10 @@ void GPBSetDoubleIvarWithFieldInternal(GPBMessage *self,
double *typePtr = (double *)&storage[field->description_->offset];
*typePtr = value;
// proto2: any value counts as having been set; proto3, it
- // has to be a non zero value.
- BOOL hasValue =
- (syntax == GPBFileSyntaxProto2) || (value != (double)0);
+ // has to be a non zero value or be in a oneof.
+ BOOL hasValue = ((syntax == GPBFileSyntaxProto2)
+ || (value != (double)0)
+ || (field->containingOneof_ != NULL));
GPBSetHasIvarField(self, field, hasValue);
GPBBecomeVisibleToAutocreator(self);
}
@@ -1052,7 +1113,15 @@ static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) {
case '\'': [destStr appendString:@"\\\'"]; break;
case '\\': [destStr appendString:@"\\\\"]; break;
default:
- [destStr appendFormat:@"%C", aChar];
+ // This differs slightly from the C++ code in that the C++ doesn't
+ // generate UTF8; it looks at the string in UTF8, but escapes every
+ // byte > 0x7E.
+ if (aChar < 0x20) {
+ [destStr appendFormat:@"\\%d%d%d",
+ (aChar / 64), ((aChar % 64) / 8), (aChar % 8)];
+ } else {
+ [destStr appendFormat:@"%C", aChar];
+ }
break;
}
}
diff --git a/objectivec/GPBUtilities_PackagePrivate.h b/objectivec/GPBUtilities_PackagePrivate.h
index c02493b2..274351b7 100644
--- a/objectivec/GPBUtilities_PackagePrivate.h
+++ b/objectivec/GPBUtilities_PackagePrivate.h
@@ -50,6 +50,17 @@ CF_EXTERN_C_BEGIN
// These two are used to inject a runtime check for version mismatch into the
// generated sources to make sure they are linked with a supporting runtime.
+void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion);
+GPB_INLINE void GPB_DEBUG_CHECK_RUNTIME_VERSIONS() {
+ // NOTE: By being inline here, this captures the value from the library's
+ // headers at the time the generated code was compiled.
+#if defined(DEBUG) && DEBUG
+ GPBCheckRuntimeVersionSupport(GOOGLE_PROTOBUF_OBJC_VERSION);
+#endif
+}
+
+// Legacy version of the checks, remove when GOOGLE_PROTOBUF_OBJC_GEN_VERSION
+// goes away (see more info in GPBBootstrap.h).
void GPBCheckRuntimeVersionInternal(int32_t version);
GPB_INLINE void GPBDebugCheckRuntimeVersion() {
#if defined(DEBUG) && DEBUG
@@ -96,7 +107,7 @@ GPB_INLINE int64_t GPBLogicalRightShift64(int64_t value, int32_t spaces) {
// negative values must be sign-extended to 64 bits to be varint encoded,
// thus always taking 10 bytes on the wire.)
GPB_INLINE int32_t GPBDecodeZigZag32(uint32_t n) {
- return GPBLogicalRightShift32(n, 1) ^ -(n & 1);
+ return (int32_t)(GPBLogicalRightShift32((int32_t)n, 1) ^ -((int32_t)(n) & 1));
}
// Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
@@ -104,7 +115,7 @@ GPB_INLINE int32_t GPBDecodeZigZag32(uint32_t n) {
// negative values must be sign-extended to 64 bits to be varint encoded,
// thus always taking 10 bytes on the wire.)
GPB_INLINE int64_t GPBDecodeZigZag64(uint64_t n) {
- return GPBLogicalRightShift64(n, 1) ^ -(n & 1);
+ return (int64_t)(GPBLogicalRightShift64((int64_t)n, 1) ^ -((int64_t)(n) & 1));
}
// Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers
@@ -113,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 (n << 1) ^ (n >> 31);
+ return (uint32_t)((n << 1) ^ (n >> 31));
}
// Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
@@ -122,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 (n << 1) ^ (n >> 63);
+ return (uint64_t)((n << 1) ^ (n >> 63));
}
#pragma clang diagnostic push
diff --git a/objectivec/GPBWellKnownTypes.h b/objectivec/GPBWellKnownTypes.h
index 311ac58e..90d96c6f 100644
--- a/objectivec/GPBWellKnownTypes.h
+++ b/objectivec/GPBWellKnownTypes.h
@@ -37,27 +37,198 @@
#endif
#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
+ #import <Protobuf/Any.pbobjc.h>
#import <Protobuf/Duration.pbobjc.h>
#import <Protobuf/Timestamp.pbobjc.h>
#else
+ #import "google/protobuf/Any.pbobjc.h"
#import "google/protobuf/Duration.pbobjc.h"
#import "google/protobuf/Timestamp.pbobjc.h"
#endif
NS_ASSUME_NONNULL_BEGIN
-// Extension to GPBTimestamp to work with standard Foundation time/date types.
+#pragma mark - Errors
+
+/** NSError domain used for errors. */
+extern NSString *const GPBWellKnownTypesErrorDomain;
+
+/** Error code for NSError with GPBWellKnownTypesErrorDomain. */
+typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) {
+ /** The type_url could not be computed for the requested GPBMessage class. */
+ GPBWellKnownTypesErrorCodeFailedToComputeTypeURL = -100,
+ /** type_url in a Any doesn’t match that of the requested GPBMessage class. */
+ GPBWellKnownTypesErrorCodeTypeURLMismatch = -101,
+};
+
+#pragma mark - GPBTimestamp
+
+/**
+ * Category for GPBTimestamp to work with standard Foundation time/date types.
+ **/
@interface GPBTimestamp (GBPWellKnownTypes)
+
+/** The NSDate representation of this GPBTimestamp. */
@property(nonatomic, readwrite, strong) NSDate *date;
+
+/**
+ * The NSTimeInterval representation of this GPBTimestamp.
+ *
+ * @note: Not all second/nanos combinations can be represented in a
+ * NSTimeInterval, so getting this could be a lossy transform.
+ **/
@property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970;
+
+/**
+ * Initializes a GPBTimestamp with the given NSDate.
+ *
+ * @param date The date to configure the GPBTimestamp with.
+ *
+ * @return A newly initialized GPBTimestamp.
+ **/
- (instancetype)initWithDate:(NSDate *)date;
+
+/**
+ * Initializes a GPBTimestamp with the given NSTimeInterval.
+ *
+ * @param timeIntervalSince1970 Time interval to configure the GPBTimestamp with.
+ *
+ * @return A newly initialized GPBTimestamp.
+ **/
- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970;
+
@end
-// Extension to GPBDuration to work with standard Foundation time type.
+#pragma mark - GPBDuration
+
+/**
+ * Category for GPBDuration to work with standard Foundation time type.
+ **/
@interface GPBDuration (GBPWellKnownTypes)
+
+/**
+ * The NSTimeInterval representation of this GPBDuration.
+ *
+ * @note: Not all second/nanos combinations can be represented in a
+ * NSTimeInterval, so getting this could be a lossy transform.
+ **/
@property(nonatomic, readwrite) NSTimeInterval timeIntervalSince1970;
+
+/**
+ * Initializes a GPBDuration with the given NSTimeInterval.
+ *
+ * @param timeIntervalSince1970 Time interval to configure the GPBDuration with.
+ *
+ * @return A newly initialized GPBDuration.
+ **/
- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970;
+
+@end
+
+#pragma mark - GPBAny
+
+/**
+ * Category for GPBAny to help work with the message within the object.
+ **/
+@interface GPBAny (GBPWellKnownTypes)
+
+/**
+ * Convenience method to create a GPBAny containing the serialized message.
+ * This uses type.googleapis.com/ as the type_url's prefix.
+ *
+ * @param message The message to be packed into the GPBAny.
+ * @param errorPtr Pointer to an error that will be populated if something goes
+ * wrong.
+ *
+ * @return A newly configured GPBAny with the given message, or nil on failure.
+ */
++ (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message
+ error:(NSError **)errorPtr;
+
+/**
+ * Convenience method to create a GPBAny containing the serialized message.
+ *
+ * @param message The message to be packed into the GPBAny.
+ * @param typeURLPrefix The URL prefix to apply for type_url.
+ * @param errorPtr Pointer to an error that will be populated if something
+ * goes wrong.
+ *
+ * @return A newly configured GPBAny with the given message, or nil on failure.
+ */
++ (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message
+ typeURLPrefix:(nonnull NSString *)typeURLPrefix
+ error:(NSError **)errorPtr;
+
+/**
+ * Initializes a GPBAny to contain the serialized message. This uses
+ * type.googleapis.com/ as the type_url's prefix.
+ *
+ * @param message The message to be packed into the GPBAny.
+ * @param errorPtr Pointer to an error that will be populated if something goes
+ * wrong.
+ *
+ * @return A newly configured GPBAny with the given message, or nil on failure.
+ */
+- (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message
+ error:(NSError **)errorPtr;
+
+/**
+ * Initializes a GPBAny to contain the serialized message.
+ *
+ * @param message The message to be packed into the GPBAny.
+ * @param typeURLPrefix The URL prefix to apply for type_url.
+ * @param errorPtr Pointer to an error that will be populated if something
+ * goes wrong.
+ *
+ * @return A newly configured GPBAny with the given message, or nil on failure.
+ */
+- (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message
+ typeURLPrefix:(nonnull NSString *)typeURLPrefix
+ error:(NSError **)errorPtr;
+
+/**
+ * Packs the serialized message into this GPBAny. This uses
+ * type.googleapis.com/ as the type_url's prefix.
+ *
+ * @param message The message to be packed into the GPBAny.
+ * @param errorPtr Pointer to an error that will be populated if something goes
+ * wrong.
+ *
+ * @return Whether the packing was successful or not.
+ */
+- (BOOL)packWithMessage:(nonnull GPBMessage *)message
+ error:(NSError **)errorPtr;
+
+/**
+ * Packs the serialized message into this GPBAny.
+ *
+ * @param message The message to be packed into the GPBAny.
+ * @param typeURLPrefix The URL prefix to apply for type_url.
+ * @param errorPtr Pointer to an error that will be populated if something
+ * goes wrong.
+ *
+ * @return Whether the packing was successful or not.
+ */
+- (BOOL)packWithMessage:(nonnull GPBMessage *)message
+ typeURLPrefix:(nonnull NSString *)typeURLPrefix
+ error:(NSError **)errorPtr;
+
+/**
+ * Unpacks the serialized message as if it was an instance of the given class.
+ *
+ * @note When checking type_url, the base URL is not checked, only the fully
+ * qualified name.
+ *
+ * @param messageClass The class to use to deserialize the contained message.
+ * @param errorPtr Pointer to an error that will be populated if something
+ * goes wrong.
+ *
+ * @return An instance of the given class populated with the contained data, or
+ * nil on failure.
+ */
+- (nullable GPBMessage *)unpackMessageClass:(Class)messageClass
+ error:(NSError **)errorPtr;
+
@end
NS_ASSUME_NONNULL_END
diff --git a/objectivec/GPBWellKnownTypes.m b/objectivec/GPBWellKnownTypes.m
index 5cdd62d5..ed798a2e 100644
--- a/objectivec/GPBWellKnownTypes.m
+++ b/objectivec/GPBWellKnownTypes.m
@@ -34,6 +34,13 @@
#import "GPBWellKnownTypes.h"
+#import "GPBUtilities_PackagePrivate.h"
+
+NSString *const GPBWellKnownTypesErrorDomain =
+ GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain);
+
+static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/";
+
static NSTimeInterval TimeIntervalSince1970FromSecondsAndNanos(int64_t seconds,
int32_t nanos) {
return seconds + (NSTimeInterval)nanos / 1e9;
@@ -48,6 +55,30 @@ static int32_t SecondsAndNanosFromTimeIntervalSince1970(NSTimeInterval time,
return (int32_t)nanos;
}
+static NSString *BuildTypeURL(NSString *typeURLPrefix, NSString *fullName) {
+ if (typeURLPrefix.length == 0) {
+ return fullName;
+ }
+
+ if ([typeURLPrefix hasSuffix:@"/"]) {
+ return [typeURLPrefix stringByAppendingString:fullName];
+ }
+
+ return [NSString stringWithFormat:@"%@/%@", typeURLPrefix, fullName];
+}
+
+static NSString *ParseTypeFromURL(NSString *typeURLString) {
+ NSRange range = [typeURLString rangeOfString:@"/" options:NSBackwardsSearch];
+ if ((range.location == NSNotFound) ||
+ (NSMaxRange(range) == typeURLString.length)) {
+ return nil;
+ }
+ NSString *result = [typeURLString substringFromIndex:range.location + 1];
+ return result;
+}
+
+#pragma mark - GPBTimestamp
+
@implementation GPBTimestamp (GBPWellKnownTypes)
- (instancetype)initWithDate:(NSDate *)date {
@@ -87,6 +118,8 @@ static int32_t SecondsAndNanosFromTimeIntervalSince1970(NSTimeInterval time,
@end
+#pragma mark - GPBDuration
+
@implementation GPBDuration (GBPWellKnownTypes)
- (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 {
@@ -113,3 +146,105 @@ static int32_t SecondsAndNanosFromTimeIntervalSince1970(NSTimeInterval time,
}
@end
+
+#pragma mark - GPBAny
+
+@implementation GPBAny (GBPWellKnownTypes)
+
++ (instancetype)anyWithMessage:(GPBMessage *)message
+ error:(NSError **)errorPtr {
+ return [self anyWithMessage:message
+ typeURLPrefix:kTypePrefixGoogleApisCom
+ error:errorPtr];
+}
+
++ (instancetype)anyWithMessage:(GPBMessage *)message
+ typeURLPrefix:(NSString *)typeURLPrefix
+ error:(NSError **)errorPtr {
+ return [[[self alloc] initWithMessage:message
+ typeURLPrefix:typeURLPrefix
+ error:errorPtr] autorelease];
+}
+
+- (instancetype)initWithMessage:(GPBMessage *)message
+ error:(NSError **)errorPtr {
+ return [self initWithMessage:message
+ typeURLPrefix:kTypePrefixGoogleApisCom
+ error:errorPtr];
+}
+
+- (instancetype)initWithMessage:(GPBMessage *)message
+ typeURLPrefix:(NSString *)typeURLPrefix
+ error:(NSError **)errorPtr {
+ self = [self init];
+ if (self) {
+ if (![self packWithMessage:message
+ typeURLPrefix:typeURLPrefix
+ error:errorPtr]) {
+ [self release];
+ self = nil;
+ }
+ }
+ return self;
+}
+
+- (BOOL)packWithMessage:(GPBMessage *)message
+ error:(NSError **)errorPtr {
+ return [self packWithMessage:message
+ typeURLPrefix:kTypePrefixGoogleApisCom
+ error:errorPtr];
+}
+
+- (BOOL)packWithMessage:(GPBMessage *)message
+ typeURLPrefix:(NSString *)typeURLPrefix
+ error:(NSError **)errorPtr {
+ NSString *fullName = [message descriptor].fullName;
+ if (fullName.length == 0) {
+ if (errorPtr) {
+ *errorPtr =
+ [NSError errorWithDomain:GPBWellKnownTypesErrorDomain
+ code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL
+ userInfo:nil];
+ }
+ return NO;
+ }
+ if (errorPtr) {
+ *errorPtr = nil;
+ }
+ self.typeURL = BuildTypeURL(typeURLPrefix, fullName);
+ self.value = message.data;
+ return YES;
+}
+
+- (GPBMessage *)unpackMessageClass:(Class)messageClass
+ error:(NSError **)errorPtr {
+ NSString *fullName = [messageClass descriptor].fullName;
+ if (fullName.length == 0) {
+ if (errorPtr) {
+ *errorPtr =
+ [NSError errorWithDomain:GPBWellKnownTypesErrorDomain
+ code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL
+ userInfo:nil];
+ }
+ return nil;
+ }
+
+ NSString *expectedFullName = ParseTypeFromURL(self.typeURL);
+ if ((expectedFullName == nil) || ![expectedFullName isEqual:fullName]) {
+ if (errorPtr) {
+ *errorPtr =
+ [NSError errorWithDomain:GPBWellKnownTypesErrorDomain
+ code:GPBWellKnownTypesErrorCodeTypeURLMismatch
+ userInfo:nil];
+ }
+ return nil;
+ }
+
+ // Any is proto3, which means no extensions, so this assumes anything put
+ // within an any also won't need extensions. A second helper could be added
+ // if needed.
+ return [messageClass parseFromData:self.value
+ error:errorPtr];
+}
+
+@end
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
index 32067910..7ce5d54f 100644
--- a/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_OSX.xcodeproj/project.pbxproj
@@ -65,6 +65,7 @@
F4E675A11B21D0000054530B /* Struct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675911B21D0000054530B /* Struct.pbobjc.m */; };
F4E675A31B21D0000054530B /* Type.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675931B21D0000054530B /* Type.pbobjc.m */; };
F4E675A51B21D0000054530B /* Wrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675951B21D0000054530B /* Wrappers.pbobjc.m */; };
+ F4F8D8831D789FD9002CE128 /* GPBUnittestProtos2.m in Sources */ = {isa = PBXBuildFile; fileRef = F4F8D8811D789FCE002CE128 /* GPBUnittestProtos2.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -211,6 +212,7 @@
F4E675AB1B21D05C0054530B /* struct.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = struct.proto; path = ../src/google/protobuf/struct.proto; sourceTree = "<group>"; };
F4E675AC1B21D05C0054530B /* type.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = type.proto; path = ../src/google/protobuf/type.proto; sourceTree = "<group>"; };
F4E675AD1B21D05C0054530B /* wrappers.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = wrappers.proto; path = ../src/google/protobuf/wrappers.proto; sourceTree = "<group>"; };
+ F4F8D8811D789FCE002CE128 /* GPBUnittestProtos2.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos2.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -408,6 +410,7 @@
7461B6AB0F94FDF800A0C422 /* GPBTestUtilities.h */,
7461B6AC0F94FDF800A0C422 /* GPBTestUtilities.m */,
8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */,
+ F4F8D8811D789FCE002CE128 /* GPBUnittestProtos2.m */,
7461B6B80F94FDF900A0C422 /* GPBUnknownFieldSetTest.m */,
7461B6BA0F94FDF900A0C422 /* GPBUtilitiesTests.m */,
8B4248DB1A92933A00BC1EC6 /* GPBWellKnownTypesTest.m */,
@@ -553,9 +556,10 @@
attributes = {
LastSwiftUpdateCheck = 0710;
LastTestingUpgradeCheck = 0600;
- LastUpgradeCheck = 0710;
+ LastUpgradeCheck = 0800;
TargetAttributes = {
8BBEA4A5147C727100C4ADB7 = {
+ LastSwiftMigration = 0800;
TestTargetID = 8B9A5EA41831993600A9D33B;
};
F45BBC141B0CE3C6002D064D = {
@@ -659,6 +663,7 @@
F4B51B1E1BBC610700744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */,
F4487C7F1AAF62CD00531423 /* GPBMessageTests+Serialization.m in Sources */,
8B4248DC1A92933A00BC1EC6 /* GPBWellKnownTypesTest.m in Sources */,
+ F4F8D8831D789FD9002CE128 /* GPBUnittestProtos2.m in Sources */,
F4353D1D1AB8822D005A6198 /* GPBDescriptorTests.m in Sources */,
8B4248BB1A8C256A00BC1EC6 /* GPBSwiftTests.swift in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
@@ -736,6 +741,7 @@
PRODUCT_NAME = UnitTests;
SWIFT_OBJC_BRIDGING_HEADER = "Tests/UnitTests-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
WARNING_CFLAGS = (
"$(inherited)",
"-Wno-documentation-unknown-command",
@@ -760,6 +766,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "com.yourcompany.${PRODUCT_NAME:identifier}";
PRODUCT_NAME = UnitTests;
SWIFT_OBJC_BRIDGING_HEADER = "Tests/UnitTests-Bridging-Header.h";
+ SWIFT_VERSION = 3.0;
WARNING_CFLAGS = (
"$(inherited)",
"-Wno-documentation-unknown-command",
@@ -778,18 +785,24 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES;
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
+ CLANG_WARN_ASSIGN_ENUM = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = YES;
CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES;
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = c99;
+ GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1";
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
@@ -838,18 +851,24 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES;
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
+ CLANG_WARN_ASSIGN_ENUM = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = YES;
CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES;
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = c99;
+ GCC_NO_COMMON_BLOCKS = YES;
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES;
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
@@ -875,6 +894,7 @@
MACOSX_DEPLOYMENT_TARGET = 10.9;
RUN_CLANG_STATIC_ANALYZER = YES;
SDKROOT = macosx;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
WARNING_CFLAGS = (
"-Wdocumentation-unknown-command",
"-Wundef",
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
index 25814c5f..2f618131 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 = "0710"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_OSX.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
index 3eb4f92b..b1243b79 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 = "0710"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
index 9f688f8d..5f599719 100644
--- a/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
+++ b/objectivec/ProtocolBuffers_iOS.xcodeproj/project.pbxproj
@@ -73,6 +73,7 @@
F4E675D51B21D1620054530B /* Struct.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675C21B21D1440054530B /* Struct.pbobjc.m */; };
F4E675D61B21D1620054530B /* Type.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675C51B21D1440054530B /* Type.pbobjc.m */; };
F4E675D71B21D1620054530B /* Wrappers.pbobjc.m in Sources */ = {isa = PBXBuildFile; fileRef = F4E675C71B21D1440054530B /* Wrappers.pbobjc.m */; };
+ F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */ = {isa = PBXBuildFile; fileRef = F4F8D8841D78A186002CE128 /* GPBUnittestProtos2.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -234,6 +235,7 @@
F4E675DD1B21D1DE0054530B /* struct.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = struct.proto; path = ../src/google/protobuf/struct.proto; sourceTree = "<group>"; };
F4E675DE1B21D1DE0054530B /* type.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = type.proto; path = ../src/google/protobuf/type.proto; sourceTree = "<group>"; };
F4E675DF1B21D1DE0054530B /* wrappers.proto */ = {isa = PBXFileReference; lastKnownFileType = text; name = wrappers.proto; path = ../src/google/protobuf/wrappers.proto; sourceTree = "<group>"; };
+ F4F8D8841D78A186002CE128 /* GPBUnittestProtos2.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GPBUnittestProtos2.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -446,6 +448,7 @@
7461B6AB0F94FDF800A0C422 /* GPBTestUtilities.h */,
7461B6AC0F94FDF800A0C422 /* GPBTestUtilities.m */,
8BD3981E14BE59D70081D629 /* GPBUnittestProtos.m */,
+ F4F8D8841D78A186002CE128 /* GPBUnittestProtos2.m */,
7461B6B80F94FDF900A0C422 /* GPBUnknownFieldSetTest.m */,
7461B6BA0F94FDF900A0C422 /* GPBUtilitiesTests.m */,
8B4248E51A929C9900BC1EC6 /* GPBWellKnownTypesTest.m */,
@@ -630,9 +633,10 @@
attributes = {
LastSwiftUpdateCheck = 0710;
LastTestingUpgradeCheck = 0600;
- LastUpgradeCheck = 0710;
+ LastUpgradeCheck = 0800;
TargetAttributes = {
8BBEA4A5147C727100C4ADB7 = {
+ LastSwiftMigration = 0800;
TestTargetID = 8B9A5EA41831993600A9D33B;
};
F45BBC0E1B0CDB50002D064D = {
@@ -755,6 +759,7 @@
F4487C811AAF62FC00531423 /* GPBMessageTests+Serialization.m in Sources */,
8B4248E61A929C9900BC1EC6 /* GPBWellKnownTypesTest.m in Sources */,
F4353D1F1AB88243005A6198 /* GPBDescriptorTests.m in Sources */,
+ F4F8D8861D78A193002CE128 /* GPBUnittestProtos2.m in Sources */,
F4B51B1C1BBC5C7100744318 /* GPBObjectiveCPlusPlusTest.mm in Sources */,
8B4248B41A8BD96E00BC1EC6 /* GPBSwiftTests.swift in Sources */,
5102DABC1891A073002037B6 /* GPBConcurrencyTests.m in Sources */,
@@ -839,7 +844,7 @@
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ENABLE_OBJC_ARC = YES;
INFOPLIST_FILE = "$(SRCROOT)/Tests/iOSTestHarness/Info.plist";
- IPHONEOS_DEPLOYMENT_TARGET = 7.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 8.0;
PRODUCT_BUNDLE_IDENTIFIER = "com.google.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
TARGETED_DEVICE_FAMILY = "1,2";
@@ -854,7 +859,7 @@
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;
CLANG_ENABLE_OBJC_ARC = YES;
INFOPLIST_FILE = "$(SRCROOT)/Tests/iOSTestHarness/Info.plist";
- IPHONEOS_DEPLOYMENT_TARGET = 7.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 8.0;
PRODUCT_BUNDLE_IDENTIFIER = "com.google.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
TARGETED_DEVICE_FAMILY = "1,2";
@@ -876,7 +881,7 @@
"$(SRCROOT)",
);
INFOPLIST_FILE = "Tests/UnitTests-Info.plist";
- IPHONEOS_DEPLOYMENT_TARGET = 7.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
@@ -886,6 +891,7 @@
PRODUCT_NAME = UnitTests;
SWIFT_OBJC_BRIDGING_HEADER = "Tests/UnitTests-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 3.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/iOSTestHarness.app/iOSTestHarness";
WARNING_CFLAGS = (
@@ -911,7 +917,7 @@
"$(SRCROOT)",
);
INFOPLIST_FILE = "Tests/UnitTests-Info.plist";
- IPHONEOS_DEPLOYMENT_TARGET = 7.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
@@ -920,6 +926,7 @@
OTHER_LDFLAGS = "-ObjC";
PRODUCT_NAME = UnitTests;
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 = (
@@ -940,19 +947,25 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES;
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
+ CLANG_WARN_ASSIGN_ENUM = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = YES;
CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES;
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = c99;
+ GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1";
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
@@ -977,7 +990,7 @@
GCC_WARN_UNUSED_PARAMETER = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
GENERATE_PROFILING_CODE = NO;
- IPHONEOS_DEPLOYMENT_TARGET = 6.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 8.0;
ONLY_ACTIVE_ARCH = YES;
RUN_CLANG_STATIC_ANALYZER = YES;
SDKROOT = iphoneos;
@@ -1001,19 +1014,25 @@
CLANG_ANALYZER_SECURITY_INSECUREAPI_RAND = YES;
CLANG_ANALYZER_SECURITY_INSECUREAPI_STRCPY = YES;
CLANG_STATIC_ANALYZER_MODE = deep;
+ CLANG_WARN_ASSIGN_ENUM = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+ CLANG_WARN_EMPTY_BODY = YES;
+ CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_NULLABLE_TO_NONNULL_CONVERSION = YES;
CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES;
CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES;
CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES;
+ CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES_AGGRESSIVE;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
ENABLE_NS_ASSERTIONS = NO;
+ ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = c99;
+ GCC_NO_COMMON_BLOCKS = YES;
GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES;
GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES;
GCC_TREAT_WARNINGS_AS_ERRORS = YES;
@@ -1036,9 +1055,10 @@
GCC_WARN_UNUSED_PARAMETER = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
GENERATE_PROFILING_CODE = NO;
- IPHONEOS_DEPLOYMENT_TARGET = 6.1;
+ IPHONEOS_DEPLOYMENT_TARGET = 8.0;
RUN_CLANG_STATIC_ANALYZER = YES;
SDKROOT = iphoneos;
+ SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
WARNING_CFLAGS = (
"-Wdocumentation-unknown-command",
"-Wundef",
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/PerformanceTests.xcscheme
index 0b96b75f..be31c308 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 = "0710"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/objectivec/ProtocolBuffers_iOS.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme
index d53a75f9..edbe6898 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 = "0710"
+ LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
diff --git a/objectivec/Tests/GPBCodedOuputStreamTests.m b/objectivec/Tests/GPBCodedOuputStreamTests.m
index 0723b645..2ad326be 100644
--- a/objectivec/Tests/GPBCodedOuputStreamTests.m
+++ b/objectivec/Tests/GPBCodedOuputStreamTests.m
@@ -193,6 +193,32 @@
}
}
+- (void)assertWriteStringNoTag:(NSData*)data
+ value:(NSString *)value
+ context:(NSString *)contextMessage {
+ NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory];
+ GPBCodedOutputStream* output =
+ [GPBCodedOutputStream streamWithOutputStream:rawOutput];
+ [output writeStringNoTag:value];
+ [output flush];
+
+ NSData* actual =
+ [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
+ XCTAssertEqualObjects(data, actual, @"%@", contextMessage);
+
+ // Try different block sizes.
+ for (int blockSize = 1; blockSize <= 16; blockSize *= 2) {
+ rawOutput = [NSOutputStream outputStreamToMemory];
+ output = [GPBCodedOutputStream streamWithOutputStream:rawOutput
+ bufferSize:blockSize];
+ [output writeStringNoTag:value];
+ [output flush];
+
+ actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
+ XCTAssertEqualObjects(data, actual, @"%@", contextMessage);
+ }
+}
+
- (void)testWriteVarint1 {
[self assertWriteVarint:bytes(0x00) value:0];
}
@@ -337,4 +363,64 @@
XCTAssertEqualObjects(rawBytes, goldenData);
}
+- (void)testCFStringGetCStringPtrAndStringsWithNullChars {
+ // This test exists to verify that CFStrings with embedded NULLs still expose
+ // their raw buffer if they are backed by UTF8 storage. If this fails, the
+ // quick/direct access paths in GPBCodedOutputStream that depend on
+ // CFStringGetCStringPtr need to be re-evalutated (maybe just removed).
+ // And yes, we do get NULLs in strings from some servers.
+
+ char zeroTest[] = "\0Test\0String";
+ // Note: there is a \0 at the end of this since it is a c-string.
+ NSString *asNSString = [[NSString alloc] initWithBytes:zeroTest
+ length:sizeof(zeroTest)
+ encoding:NSUTF8StringEncoding];
+ const char *cString =
+ CFStringGetCStringPtr((CFStringRef)asNSString, kCFStringEncodingUTF8);
+ XCTAssertTrue(cString != NULL);
+ // Again, if the above assert fails, then it means NSString no longer exposes
+ // the raw utf8 storage of a string created from utf8 input, so the code using
+ // CFStringGetCStringPtr in GPBCodedOutputStream will still work (it will take
+ // a different code path); but the optimizations for when
+ // CFStringGetCStringPtr does work could possibly go away.
+
+ XCTAssertEqual(sizeof(zeroTest),
+ [asNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
+ XCTAssertTrue(0 == memcmp(cString, zeroTest, sizeof(zeroTest)));
+ [asNSString release];
+}
+
+- (void)testWriteStringsWithZeroChar {
+ // Unicode allows `\0` as a character, and NSString is a class cluster, so
+ // there are a few different classes that could end up beind a given string.
+ // Historically, we've seen differences based on constant strings in code and
+ // strings built via the NSString apis. So this round trips them to ensure
+ // they are acting as expected.
+
+ NSArray<NSString *> *strs = @[
+ @"\0at start",
+ @"in\0middle",
+ @"at end\0",
+ ];
+ int i = 0;
+ for (NSString *str in strs) {
+ NSData *asUTF8 = [str dataUsingEncoding:NSUTF8StringEncoding];
+ NSMutableData *expected = [NSMutableData data];
+ uint8_t lengthByte = (uint8_t)asUTF8.length;
+ [expected appendBytes:&lengthByte length:1];
+ [expected appendData:asUTF8];
+
+ NSString *context = [NSString stringWithFormat:@"Loop %d - Literal", i];
+ [self assertWriteStringNoTag:expected value:str context:context];
+
+ // Force a new string to be built which gets a different class from the
+ // NSString class cluster than the literal did.
+ NSString *str2 = [NSString stringWithFormat:@"%@", str];
+ context = [NSString stringWithFormat:@"Loop %d - Built", i];
+ [self assertWriteStringNoTag:expected value:str2 context:context];
+
+ ++i;
+ }
+}
+
@end
diff --git a/objectivec/Tests/GPBDescriptorTests.m b/objectivec/Tests/GPBDescriptorTests.m
index 74e3172b..1e1c3de8 100644
--- a/objectivec/Tests/GPBDescriptorTests.m
+++ b/objectivec/Tests/GPBDescriptorTests.m
@@ -34,12 +34,41 @@
#import "GPBDescriptor.h"
#import "google/protobuf/Unittest.pbobjc.h"
+#import "google/protobuf/UnittestObjc.pbobjc.h"
+#import "google/protobuf/Descriptor.pbobjc.h"
@interface DescriptorTests : GPBTestCase
@end
@implementation DescriptorTests
+- (void)testDescriptor_containingType {
+ GPBDescriptor *testAllTypesDesc = [TestAllTypes descriptor];
+ GPBDescriptor *nestedMessageDesc = [TestAllTypes_NestedMessage descriptor];
+ XCTAssertNil(testAllTypesDesc.containingType);
+ XCTAssertNotNil(nestedMessageDesc.containingType);
+ XCTAssertEqual(nestedMessageDesc.containingType, testAllTypesDesc); // Ptr comparison
+}
+
+- (void)testDescriptor_fullName {
+ GPBDescriptor *testAllTypesDesc = [TestAllTypes descriptor];
+ XCTAssertEqualObjects(testAllTypesDesc.fullName, @"protobuf_unittest.TestAllTypes");
+ GPBDescriptor *nestedMessageDesc = [TestAllTypes_NestedMessage descriptor];
+ XCTAssertEqualObjects(nestedMessageDesc.fullName, @"protobuf_unittest.TestAllTypes.NestedMessage");
+
+ // Prefixes removed.
+ GPBDescriptor *descDesc = [GPBDescriptorProto descriptor];
+ XCTAssertEqualObjects(descDesc.fullName, @"google.protobuf.DescriptorProto");
+ GPBDescriptor *descExtRngDesc = [GPBDescriptorProto_ExtensionRange descriptor];
+ XCTAssertEqualObjects(descExtRngDesc.fullName, @"google.protobuf.DescriptorProto.ExtensionRange");
+
+ // Things that get "_Class" added.
+ GPBDescriptor *pointDesc = [Point_Class descriptor];
+ XCTAssertEqualObjects(pointDesc.fullName, @"protobuf_unittest.Point");
+ GPBDescriptor *pointRectDesc = [Point_Rect descriptor];
+ XCTAssertEqualObjects(pointRectDesc.fullName, @"protobuf_unittest.Point.Rect");
+}
+
- (void)testFieldDescriptor {
GPBDescriptor *descriptor = [TestAllTypes descriptor];
diff --git a/objectivec/Tests/GPBMessageTests+Runtime.m b/objectivec/Tests/GPBMessageTests+Runtime.m
index 1520381b..0058311b 100644
--- a/objectivec/Tests/GPBMessageTests+Runtime.m
+++ b/objectivec/Tests/GPBMessageTests+Runtime.m
@@ -36,6 +36,7 @@
#import "google/protobuf/MapUnittest.pbobjc.h"
#import "google/protobuf/Unittest.pbobjc.h"
+#import "google/protobuf/UnittestCycle.pbobjc.h"
#import "google/protobuf/UnittestObjcStartup.pbobjc.h"
#import "google/protobuf/UnittestRuntimeProto2.pbobjc.h"
#import "google/protobuf/UnittestRuntimeProto3.pbobjc.h"
@@ -49,11 +50,24 @@
// specific.
- (void)testStartupOrdering {
- // Just have to create a message. Nothing else uses the classes from
- // this file, so the first selector invoked on the class will initialize
- // it, which also initializes the root.
+ // Message class/Root class initialization is a little tricky, so these just
+ // create some possible patterns that can be a problem. The messages don't
+ // have to be exercised, just creating them is enough to test. If there
+ // is a problem, the runtime should assert or hang.
+ //
+ // Note: the messages from these proto files should not be used in any other
+ // tests, that way when they are referenced here it will be the first use and
+ // initialization will take place now.
+
TestObjCStartupMessage *message = [TestObjCStartupMessage message];
XCTAssertNotNil(message);
+
+ CycleBaz *baz = [CycleBaz message];
+ CycleBar *bar = [CycleBar message];
+ CycleFoo *foo = [CycleFoo message];
+ XCTAssertNotNil(baz);
+ XCTAssertNotNil(bar);
+ XCTAssertNotNil(foo);
}
- (void)testProto2HasMethodSupport {
@@ -326,6 +340,17 @@
//% [msg release];
//% }
//%
+//%PDDM-DEFINE PROTO2_TEST_CLEAR_FIELD_WITH_NIL(FIELD, VALUE)
+//% { // optional##FIELD
+//% Message2 *msg = [[Message2 alloc] init];
+//% XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_Optional##FIELD));
+//% msg.optional##FIELD = VALUE;
+//% XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_Optional##FIELD));
+//% msg.optional##FIELD = nil;
+//% XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_Optional##FIELD));
+//% [msg release];
+//% }
+//%
//%PDDM-DEFINE PROTO2_TEST_HAS_FIELDS()
//%PROTO2_TEST_HAS_FIELD(Int32, 1, 0)
//%PROTO2_TEST_HAS_FIELD(Int64, 1, 0)
@@ -347,6 +372,14 @@
//% //
//%
//%PROTO2_TEST_HAS_FIELD(Enum, Message2_Enum_Bar, Message2_Enum_Foo)
+//% //
+//% // Nil can also be used to clear strings, bytes, groups, and messages.
+//% //
+//%
+//%PROTO2_TEST_CLEAR_FIELD_WITH_NIL(String, @"foo")
+//%PROTO2_TEST_CLEAR_FIELD_WITH_NIL(Bytes, [@"foo" dataUsingEncoding:NSUTF8StringEncoding])
+//%PROTO2_TEST_CLEAR_FIELD_WITH_NIL(Group, [Message2_OptionalGroup message])
+//%PROTO2_TEST_CLEAR_FIELD_WITH_NIL(Message, [Message2 message])
//%PDDM-EXPAND PROTO2_TEST_HAS_FIELDS()
// This block of code is generated, do not edit it directly.
@@ -658,13 +691,57 @@
[msg release];
}
+ //
+ // Nil can also be used to clear strings, bytes, groups, and messages.
+ //
+
+ { // optionalString
+ Message2 *msg = [[Message2 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalString));
+ msg.optionalString = @"foo";
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalString));
+ msg.optionalString = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalString));
+ [msg release];
+ }
+
+ { // optionalBytes
+ Message2 *msg = [[Message2 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalBytes));
+ msg.optionalBytes = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalBytes));
+ msg.optionalBytes = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalBytes));
+ [msg release];
+ }
+
+ { // optionalGroup
+ Message2 *msg = [[Message2 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalGroup));
+ msg.optionalGroup = [Message2_OptionalGroup message];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalGroup));
+ msg.optionalGroup = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalGroup));
+ [msg release];
+ }
+
+ { // optionalMessage
+ Message2 *msg = [[Message2 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalMessage));
+ msg.optionalMessage = [Message2 message];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalMessage));
+ msg.optionalMessage = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message2_FieldNumber_OptionalMessage));
+ [msg release];
+ }
+
//%PDDM-EXPAND-END PROTO2_TEST_HAS_FIELDS()
}
- (void)testProto3SingleFieldHasBehavior {
//
- // Setting to any value including the default value (0) should result has*
- // being true.
+ // Setting to any value but the default value (0) should result has*
+ // being true. When set to the default, shouldn't be true.
//
//%PDDM-DEFINE PROTO3_TEST_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE)
@@ -678,6 +755,17 @@
//% [msg release];
//% }
//%
+//%PDDM-DEFINE PROTO3_TEST_CLEAR_FIELD_WITH_NIL(FIELD, VALUE)
+//% { // optional##FIELD
+//% Message3 *msg = [[Message3 alloc] init];
+//% XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_Optional##FIELD));
+//% msg.optional##FIELD = VALUE;
+//% XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_Optional##FIELD));
+//% msg.optional##FIELD = nil;
+//% XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_Optional##FIELD));
+//% [msg release];
+//% }
+//%
//%PDDM-DEFINE PROTO3_TEST_HAS_FIELDS()
//%PROTO3_TEST_HAS_FIELD(Int32, 1, 0)
//%PROTO3_TEST_HAS_FIELD(Int64, 1, 0)
@@ -695,10 +783,17 @@
//%PROTO3_TEST_HAS_FIELD(String, @"foo", @"")
//%PROTO3_TEST_HAS_FIELD(Bytes, [@"foo" dataUsingEncoding:NSUTF8StringEncoding], [NSData data])
//% //
-//% // Test doesn't apply to optionalGroup/optionalMessage.
+//% // Test doesn't apply to optionalMessage (no groups in proto3).
//% //
//%
//%PROTO3_TEST_HAS_FIELD(Enum, Message3_Enum_Bar, Message3_Enum_Foo)
+//% //
+//% // Nil can also be used to clear strings, bytes, and messages (no groups in proto3).
+//% //
+//%
+//%PROTO3_TEST_CLEAR_FIELD_WITH_NIL(String, @"foo")
+//%PROTO3_TEST_CLEAR_FIELD_WITH_NIL(Bytes, [@"foo" dataUsingEncoding:NSUTF8StringEncoding])
+//%PROTO3_TEST_CLEAR_FIELD_WITH_NIL(Message, [Message3 message])
//%PDDM-EXPAND PROTO3_TEST_HAS_FIELDS()
// This block of code is generated, do not edit it directly.
@@ -853,7 +948,7 @@
}
//
- // Test doesn't apply to optionalGroup/optionalMessage.
+ // Test doesn't apply to optionalMessage (no groups in proto3).
//
{ // optionalEnum
@@ -866,6 +961,40 @@
[msg release];
}
+ //
+ // Nil can also be used to clear strings, bytes, and messages (no groups in proto3).
+ //
+
+ { // optionalString
+ Message3 *msg = [[Message3 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalString));
+ msg.optionalString = @"foo";
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalString));
+ msg.optionalString = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalString));
+ [msg release];
+ }
+
+ { // optionalBytes
+ Message3 *msg = [[Message3 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalBytes));
+ msg.optionalBytes = [@"foo" dataUsingEncoding:NSUTF8StringEncoding];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalBytes));
+ msg.optionalBytes = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalBytes));
+ [msg release];
+ }
+
+ { // optionalMessage
+ Message3 *msg = [[Message3 alloc] init];
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalMessage));
+ msg.optionalMessage = [Message3 message];
+ XCTAssertTrue(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalMessage));
+ msg.optionalMessage = nil;
+ XCTAssertFalse(GPBMessageHasFieldNumberSet(msg, Message3_FieldNumber_OptionalMessage));
+ [msg release];
+ }
+
//%PDDM-EXPAND-END PROTO3_TEST_HAS_FIELDS()
}
@@ -1972,6 +2101,262 @@
[msg release];
}
+- (void)testProto2OneofSetToDefault {
+
+ // proto3 doesn't normally write out zero (default) fields, but if they are
+ // in a oneof it does. proto2 doesn't have this special behavior, but we
+ // still confirm setting to the explicit default does set the case to be
+ // sure the runtime is working correctly.
+
+ NSString *oneofStringDefault = @"string";
+ NSData *oneofBytesDefault = [@"data" dataUsingEncoding:NSUTF8StringEncoding];
+
+ Message2 *msg = [[Message2 alloc] init];
+
+ uint32_t values[] = {
+ Message2_O_OneOfCase_OneofInt32,
+ Message2_O_OneOfCase_OneofInt64,
+ Message2_O_OneOfCase_OneofUint32,
+ Message2_O_OneOfCase_OneofUint64,
+ Message2_O_OneOfCase_OneofSint32,
+ Message2_O_OneOfCase_OneofSint64,
+ Message2_O_OneOfCase_OneofFixed32,
+ Message2_O_OneOfCase_OneofFixed64,
+ Message2_O_OneOfCase_OneofSfixed32,
+ Message2_O_OneOfCase_OneofSfixed64,
+ Message2_O_OneOfCase_OneofFloat,
+ Message2_O_OneOfCase_OneofDouble,
+ Message2_O_OneOfCase_OneofBool,
+ Message2_O_OneOfCase_OneofString,
+ Message2_O_OneOfCase_OneofBytes,
+ // Skip group
+ // Skip message
+ Message2_O_OneOfCase_OneofEnum,
+ };
+
+ for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) {
+ switch (values[i]) {
+ case Message2_O_OneOfCase_OneofInt32:
+ msg.oneofInt32 = 100;
+ break;
+ case Message2_O_OneOfCase_OneofInt64:
+ msg.oneofInt64 = 101;
+ break;
+ case Message2_O_OneOfCase_OneofUint32:
+ msg.oneofUint32 = 102;
+ break;
+ case Message2_O_OneOfCase_OneofUint64:
+ msg.oneofUint64 = 103;
+ break;
+ case Message2_O_OneOfCase_OneofSint32:
+ msg.oneofSint32 = 104;
+ break;
+ case Message2_O_OneOfCase_OneofSint64:
+ msg.oneofSint64 = 105;
+ break;
+ case Message2_O_OneOfCase_OneofFixed32:
+ msg.oneofFixed32 = 106;
+ break;
+ case Message2_O_OneOfCase_OneofFixed64:
+ msg.oneofFixed64 = 107;
+ break;
+ case Message2_O_OneOfCase_OneofSfixed32:
+ msg.oneofSfixed32 = 108;
+ break;
+ case Message2_O_OneOfCase_OneofSfixed64:
+ msg.oneofSfixed64 = 109;
+ break;
+ case Message2_O_OneOfCase_OneofFloat:
+ msg.oneofFloat = 110.0f;
+ break;
+ case Message2_O_OneOfCase_OneofDouble:
+ msg.oneofDouble = 111.0;
+ break;
+ case Message2_O_OneOfCase_OneofBool:
+ msg.oneofBool = YES;
+ break;
+ case Message2_O_OneOfCase_OneofString:
+ msg.oneofString = oneofStringDefault;
+ break;
+ case Message2_O_OneOfCase_OneofBytes:
+ msg.oneofBytes = oneofBytesDefault;
+ break;
+ case Message2_O_OneOfCase_OneofEnum:
+ msg.oneofEnum = Message3_Enum_Baz;
+ break;
+ default:
+ XCTFail(@"shouldn't happen, loop: %zd, value: %d", i, values[i]);
+ break;
+ }
+
+ // Should be set to the correct case.
+ XCTAssertEqual(msg.oOneOfCase, values[i], "Loop: %zd", i);
+
+ // Confirm everything is the defaults.
+ XCTAssertEqual(msg.oneofInt32, 100, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofInt64, 101, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofUint32, 102U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofUint64, 103U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSint32, 104, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSint64, 105, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofFixed32, 106U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofFixed64, 107U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSfixed32, 108, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSfixed64, 109, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofFloat, 110.0f, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofDouble, 111.0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofBool, YES, "Loop: %zd", i);
+ XCTAssertEqualObjects(msg.oneofString, oneofStringDefault, "Loop: %zd", i);
+ XCTAssertEqualObjects(msg.oneofBytes, oneofBytesDefault, "Loop: %zd", i);
+ // Skip group, no default to consider.
+ // Skip message, no default to consider.
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum_Baz, "Loop: %zd", i);
+ }
+
+ // We special case nil on string, data, group, and message, ensure they work
+ // as expected. i.e. - it clears the case.
+ msg.oneofString = nil;
+ XCTAssertEqualObjects(msg.oneofString, oneofStringDefault);
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase_GPBUnsetOneOfCase);
+ msg.oneofBytes = nil;
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase_GPBUnsetOneOfCase);
+ XCTAssertEqualObjects(msg.oneofBytes, oneofBytesDefault);
+ msg.oneofGroup = nil;
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase_GPBUnsetOneOfCase);
+ XCTAssertNotNil(msg.oneofGroup);
+ msg.oneofMessage = nil;
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase_GPBUnsetOneOfCase);
+ XCTAssertNotNil(msg.oneofMessage);
+
+ [msg release];
+}
+
+- (void)testProto3OneofSetToZero {
+
+ // Normally setting a proto3 field to the zero value should result in it being
+ // reset/cleared. But in a oneof, it still gets recored so it can go out
+ // over the wire and the other side can see what was set in the oneof.
+
+ NSString *oneofStringDefault = @"";
+ NSData *oneofBytesDefault = [NSData data];
+
+ Message3 *msg = [[Message3 alloc] init];
+
+ uint32_t values[] = {
+ Message3_O_OneOfCase_OneofInt32,
+ Message3_O_OneOfCase_OneofInt64,
+ Message3_O_OneOfCase_OneofUint32,
+ Message3_O_OneOfCase_OneofUint64,
+ Message3_O_OneOfCase_OneofSint32,
+ Message3_O_OneOfCase_OneofSint64,
+ Message3_O_OneOfCase_OneofFixed32,
+ Message3_O_OneOfCase_OneofFixed64,
+ Message3_O_OneOfCase_OneofSfixed32,
+ Message3_O_OneOfCase_OneofSfixed64,
+ Message3_O_OneOfCase_OneofFloat,
+ Message3_O_OneOfCase_OneofDouble,
+ Message3_O_OneOfCase_OneofBool,
+ Message3_O_OneOfCase_OneofString,
+ Message3_O_OneOfCase_OneofBytes,
+ Message3_O_OneOfCase_OneofMessage,
+ Message3_O_OneOfCase_OneofEnum,
+ };
+
+ for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) {
+ switch (values[i]) {
+ case Message3_O_OneOfCase_OneofInt32:
+ msg.oneofInt32 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofInt64:
+ msg.oneofInt64 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofUint32:
+ msg.oneofUint32 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofUint64:
+ msg.oneofUint64 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofSint32:
+ msg.oneofSint32 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofSint64:
+ msg.oneofSint64 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofFixed32:
+ msg.oneofFixed32 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofFixed64:
+ msg.oneofFixed64 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofSfixed32:
+ msg.oneofSfixed32 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofSfixed64:
+ msg.oneofSfixed64 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofFloat:
+ msg.oneofFloat = 0.0f;
+ break;
+ case Message3_O_OneOfCase_OneofDouble:
+ msg.oneofDouble = 0.0;
+ break;
+ case Message3_O_OneOfCase_OneofBool:
+ msg.oneofBool = NO;
+ break;
+ case Message3_O_OneOfCase_OneofString:
+ msg.oneofString = oneofStringDefault;
+ break;
+ case Message3_O_OneOfCase_OneofBytes:
+ msg.oneofBytes = oneofBytesDefault;
+ break;
+ case Message3_O_OneOfCase_OneofMessage:
+ msg.oneofMessage.optionalInt32 = 0;
+ break;
+ case Message3_O_OneOfCase_OneofEnum:
+ msg.oneofEnum = Message3_Enum_Foo;
+ break;
+ default:
+ XCTFail(@"shouldn't happen, loop: %zd, value: %d", i, values[i]);
+ break;
+ }
+
+ // Should be set to the correct case.
+ XCTAssertEqual(msg.oOneOfCase, values[i], "Loop: %zd", i);
+
+ // Confirm everything is still zeros.
+ XCTAssertEqual(msg.oneofInt32, 0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofInt64, 0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofUint32, 0U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofUint64, 0U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSint32, 0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSint64, 0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofFixed32, 0U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofFixed64, 0U, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSfixed32, 0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofSfixed64, 0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofFloat, 0.0f, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofDouble, 0.0, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofBool, NO, "Loop: %zd", i);
+ XCTAssertEqualObjects(msg.oneofString, oneofStringDefault, "Loop: %zd", i);
+ XCTAssertEqualObjects(msg.oneofBytes, oneofBytesDefault, "Loop: %zd", i);
+ XCTAssertNotNil(msg.oneofMessage, "Loop: %zd", i);
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum_Foo, "Loop: %zd", i);
+ }
+
+ // We special case nil on string, data, message, ensure they work as expected.
+ msg.oneofString = nil;
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase_GPBUnsetOneOfCase);
+ XCTAssertEqualObjects(msg.oneofString, oneofStringDefault);
+ msg.oneofBytes = nil;
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase_GPBUnsetOneOfCase);
+ XCTAssertEqualObjects(msg.oneofBytes, oneofBytesDefault);
+ msg.oneofMessage = nil;
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase_GPBUnsetOneOfCase);
+ XCTAssertNotNil(msg.oneofMessage);
+
+ [msg release];
+}
+
- (void)testCopyingMakesUniqueObjects {
const int repeatCount = 5;
TestAllTypes *msg1 = [TestAllTypes message];
diff --git a/objectivec/Tests/GPBSwiftTests.swift b/objectivec/Tests/GPBSwiftTests.swift
index b5999c21..9d8a0fae 100644
--- a/objectivec/Tests/GPBSwiftTests.swift
+++ b/objectivec/Tests/GPBSwiftTests.swift
@@ -42,23 +42,23 @@ class GPBBridgeTests: XCTestCase {
msg.optionalInt32 = 100
msg.optionalString = "abc"
- msg.optionalEnum = .Bar
+ msg.optionalEnum = .bar
msg2.optionalString = "other"
- msg.optionalMessage = msg2
+ msg.optional = msg2
msg3.a = 200
msg.optionalGroup = msg3
msg.repeatedInt32Array.addValue(300)
msg.repeatedInt32Array.addValue(301)
- msg.repeatedStringArray.addObject("mno")
- msg.repeatedStringArray.addObject("pqr")
- msg.repeatedEnumArray.addValue(Message2_Enum.Bar.rawValue)
- msg.repeatedEnumArray.addValue(Message2_Enum.Baz.rawValue)
+ msg.repeatedStringArray.add("mno")
+ msg.repeatedStringArray.add("pqr")
+ msg.repeatedEnumArray.addValue(Message2_Enum.bar.rawValue)
+ msg.repeatedEnumArray.addValue(Message2_Enum.baz.rawValue)
msg.mapInt32Int32.setInt32(400, forKey:500)
msg.mapInt32Int32.setInt32(401, forKey:501)
- msg.mapStringString.setObject("foo", forKey:"bar")
- msg.mapStringString.setObject("abc", forKey:"xyz")
- msg.mapInt32Enum.setEnum(Message2_Enum.Bar.rawValue, forKey:600)
- msg.mapInt32Enum.setEnum(Message2_Enum.Baz.rawValue, forKey:601)
+ msg.mapStringString.setObject("foo", forKey:"bar" as NSString)
+ msg.mapStringString.setObject("abc", forKey:"xyz" as NSString)
+ msg.mapInt32Enum.setEnum(Message2_Enum.bar.rawValue, forKey:600)
+ msg.mapInt32Enum.setEnum(Message2_Enum.baz.rawValue, forKey:601)
// Check has*.
XCTAssertTrue(msg.hasOptionalInt32)
@@ -75,19 +75,19 @@ class GPBBridgeTests: XCTestCase {
XCTAssertEqual(msg.optionalInt32, Int32(100))
XCTAssertEqual(msg.optionalString, "abc")
XCTAssertEqual(msg2.optionalString, "other")
- XCTAssertTrue(msg.optionalMessage === msg2)
- XCTAssertEqual(msg.optionalEnum, Message2_Enum.Bar)
+ XCTAssertTrue(msg.optional === msg2)
+ XCTAssertEqual(msg.optionalEnum, Message2_Enum.bar)
XCTAssertEqual(msg3.a, Int32(200))
XCTAssertTrue(msg.optionalGroup === msg3)
XCTAssertEqual(msg.repeatedInt32Array.count, UInt(2))
- XCTAssertEqual(msg.repeatedInt32Array.valueAtIndex(0), Int32(300))
- XCTAssertEqual(msg.repeatedInt32Array.valueAtIndex(1), Int32(301))
+ XCTAssertEqual(msg.repeatedInt32Array.value(at: 0), Int32(300))
+ XCTAssertEqual(msg.repeatedInt32Array.value(at: 1), Int32(301))
XCTAssertEqual(msg.repeatedStringArray.count, Int(2))
- XCTAssertEqual(msg.repeatedStringArray.objectAtIndex(0) as? String, "mno")
- XCTAssertEqual(msg.repeatedStringArray.objectAtIndex(1) as? String, "pqr")
+ XCTAssertEqual(msg.repeatedStringArray.object(at: 0) as? String, "mno")
+ XCTAssertEqual(msg.repeatedStringArray.object(at: 1) as? String, "pqr")
XCTAssertEqual(msg.repeatedEnumArray.count, UInt(2))
- XCTAssertEqual(msg.repeatedEnumArray.valueAtIndex(0), Message2_Enum.Bar.rawValue)
- XCTAssertEqual(msg.repeatedEnumArray.valueAtIndex(1), Message2_Enum.Baz.rawValue)
+ XCTAssertEqual(msg.repeatedEnumArray.value(at: 0), Message2_Enum.bar.rawValue)
+ XCTAssertEqual(msg.repeatedEnumArray.value(at: 1), Message2_Enum.baz.rawValue)
XCTAssertEqual(msg.repeatedInt64Array.count, UInt(0))
XCTAssertEqual(msg.mapInt32Int32.count, UInt(2))
var intValue: Int32 = 0
@@ -96,13 +96,13 @@ class GPBBridgeTests: XCTestCase {
XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey: 501))
XCTAssertEqual(intValue, Int32(401))
XCTAssertEqual(msg.mapStringString.count, Int(2))
- XCTAssertEqual(msg.mapStringString.objectForKey("bar") as? String, "foo")
- XCTAssertEqual(msg.mapStringString.objectForKey("xyz") as? String, "abc")
+ XCTAssertEqual(msg.mapStringString.object(forKey: "bar") as? String, "foo")
+ XCTAssertEqual(msg.mapStringString.object(forKey: "xyz") as? String, "abc")
XCTAssertEqual(msg.mapInt32Enum.count, UInt(2))
XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:600))
- XCTAssertEqual(intValue, Message2_Enum.Bar.rawValue)
+ XCTAssertEqual(intValue, Message2_Enum.bar.rawValue)
XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:601))
- XCTAssertEqual(intValue, Message2_Enum.Baz.rawValue)
+ XCTAssertEqual(intValue, Message2_Enum.baz.rawValue)
// Clearing a string with nil.
msg2.optionalString = nil
@@ -124,8 +124,8 @@ class GPBBridgeTests: XCTestCase {
XCTAssertFalse(msg.hasOptionalFloat)
XCTAssertEqual(msg.optionalInt32, Int32(0))
XCTAssertEqual(msg.optionalString, "")
- XCTAssertTrue(msg.optionalMessage !== msg2) // New instance
- XCTAssertEqual(msg.optionalEnum, Message2_Enum.Foo) // Default
+ XCTAssertTrue(msg.optional !== msg2) // New instance
+ XCTAssertEqual(msg.optionalEnum, Message2_Enum.foo) // Default
XCTAssertEqual(msg.repeatedInt32Array.count, UInt(0))
XCTAssertEqual(msg.repeatedStringArray.count, Int(0))
XCTAssertEqual(msg.repeatedEnumArray.count, UInt(0))
@@ -140,22 +140,22 @@ class GPBBridgeTests: XCTestCase {
msg.optionalInt32 = 100
msg.optionalString = "abc"
- msg.optionalEnum = .Bar
+ msg.optionalEnum = .bar
msg2.optionalString = "other"
- msg.optionalMessage = msg2
+ msg.optional = msg2
msg.repeatedInt32Array.addValue(300)
msg.repeatedInt32Array.addValue(301)
- msg.repeatedStringArray.addObject("mno")
- msg.repeatedStringArray.addObject("pqr")
+ msg.repeatedStringArray.add("mno")
+ msg.repeatedStringArray.add("pqr")
// "proto3" syntax lets enum get unknown values.
- msg.repeatedEnumArray.addValue(Message3_Enum.Bar.rawValue)
+ msg.repeatedEnumArray.addValue(Message3_Enum.bar.rawValue)
msg.repeatedEnumArray.addRawValue(666)
SetMessage3_OptionalEnum_RawValue(msg2, 666)
msg.mapInt32Int32.setInt32(400, forKey:500)
msg.mapInt32Int32.setInt32(401, forKey:501)
- msg.mapStringString.setObject("foo", forKey:"bar")
- msg.mapStringString.setObject("abc", forKey:"xyz")
- msg.mapInt32Enum.setEnum(Message2_Enum.Bar.rawValue, forKey:600)
+ msg.mapStringString.setObject("foo", forKey:"bar" as NSString)
+ msg.mapStringString.setObject("abc", forKey:"xyz" as NSString)
+ msg.mapInt32Enum.setEnum(Message2_Enum.bar.rawValue, forKey:600)
// "proto3" syntax lets enum get unknown values.
msg.mapInt32Enum.setRawValue(666, forKey:601)
@@ -167,20 +167,20 @@ class GPBBridgeTests: XCTestCase {
XCTAssertEqual(msg.optionalInt32, Int32(100))
XCTAssertEqual(msg.optionalString, "abc")
XCTAssertEqual(msg2.optionalString, "other")
- XCTAssertTrue(msg.optionalMessage === msg2)
- XCTAssertEqual(msg.optionalEnum, Message3_Enum.Bar)
+ XCTAssertTrue(msg.optional === msg2)
+ XCTAssertEqual(msg.optionalEnum, Message3_Enum.bar)
XCTAssertEqual(msg.repeatedInt32Array.count, UInt(2))
- XCTAssertEqual(msg.repeatedInt32Array.valueAtIndex(0), Int32(300))
- XCTAssertEqual(msg.repeatedInt32Array.valueAtIndex(1), Int32(301))
+ XCTAssertEqual(msg.repeatedInt32Array.value(at: 0), Int32(300))
+ XCTAssertEqual(msg.repeatedInt32Array.value(at: 1), Int32(301))
XCTAssertEqual(msg.repeatedStringArray.count, Int(2))
- XCTAssertEqual(msg.repeatedStringArray.objectAtIndex(0) as? String, "mno")
- XCTAssertEqual(msg.repeatedStringArray.objectAtIndex(1) as? String, "pqr")
+ XCTAssertEqual(msg.repeatedStringArray.object(at: 0) as? String, "mno")
+ XCTAssertEqual(msg.repeatedStringArray.object(at: 1) as? String, "pqr")
XCTAssertEqual(msg.repeatedInt64Array.count, UInt(0))
XCTAssertEqual(msg.repeatedEnumArray.count, UInt(2))
- XCTAssertEqual(msg.repeatedEnumArray.valueAtIndex(0), Message3_Enum.Bar.rawValue)
- XCTAssertEqual(msg.repeatedEnumArray.valueAtIndex(1), Message3_Enum.GPBUnrecognizedEnumeratorValue.rawValue)
- XCTAssertEqual(msg.repeatedEnumArray.rawValueAtIndex(1), 666)
- XCTAssertEqual(msg2.optionalEnum, Message3_Enum.GPBUnrecognizedEnumeratorValue)
+ XCTAssertEqual(msg.repeatedEnumArray.value(at: 0), Message3_Enum.bar.rawValue)
+ XCTAssertEqual(msg.repeatedEnumArray.value(at: 1), Message3_Enum.gpbUnrecognizedEnumeratorValue.rawValue)
+ XCTAssertEqual(msg.repeatedEnumArray.rawValue(at: 1), 666)
+ XCTAssertEqual(msg2.optionalEnum, Message3_Enum.gpbUnrecognizedEnumeratorValue)
XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Int32(666))
XCTAssertEqual(msg.mapInt32Int32.count, UInt(2))
var intValue: Int32 = 0
@@ -189,13 +189,13 @@ class GPBBridgeTests: XCTestCase {
XCTAssertTrue(msg.mapInt32Int32.getInt32(&intValue, forKey:501))
XCTAssertEqual(intValue, Int32(401))
XCTAssertEqual(msg.mapStringString.count, Int(2))
- XCTAssertEqual(msg.mapStringString.objectForKey("bar") as? String, "foo")
- XCTAssertEqual(msg.mapStringString.objectForKey("xyz") as? String, "abc")
+ XCTAssertEqual(msg.mapStringString.object(forKey: "bar") as? String, "foo")
+ XCTAssertEqual(msg.mapStringString.object(forKey: "xyz") as? String, "abc")
XCTAssertEqual(msg.mapInt32Enum.count, UInt(2))
XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:600))
- XCTAssertEqual(intValue, Message2_Enum.Bar.rawValue)
+ XCTAssertEqual(intValue, Message2_Enum.bar.rawValue)
XCTAssertTrue(msg.mapInt32Enum.getEnum(&intValue, forKey:601))
- XCTAssertEqual(intValue, Message3_Enum.GPBUnrecognizedEnumeratorValue.rawValue)
+ XCTAssertEqual(intValue, Message3_Enum.gpbUnrecognizedEnumeratorValue.rawValue)
XCTAssertTrue(msg.mapInt32Enum.getRawValue(&intValue, forKey:601))
XCTAssertEqual(intValue, 666)
@@ -204,23 +204,23 @@ class GPBBridgeTests: XCTestCase {
XCTAssertEqual(msg2.optionalString, "")
// Clearing a message with nil.
- msg.optionalMessage = nil
+ msg.optional = nil
XCTAssertFalse(msg.hasOptionalMessage)
- XCTAssertTrue(msg.optionalMessage !== msg2) // New instance
+ XCTAssertTrue(msg.optional !== msg2) // New instance
// Clear.
msg.clear()
XCTAssertFalse(msg.hasOptionalMessage)
XCTAssertEqual(msg.optionalInt32, Int32(0))
XCTAssertEqual(msg.optionalString, "")
- XCTAssertTrue(msg.optionalMessage !== msg2) // New instance
- XCTAssertEqual(msg.optionalEnum, Message3_Enum.Foo) // Default
+ XCTAssertTrue(msg.optional !== msg2) // New instance
+ XCTAssertEqual(msg.optionalEnum, Message3_Enum.foo) // Default
XCTAssertEqual(msg.repeatedInt32Array.count, UInt(0))
XCTAssertEqual(msg.repeatedStringArray.count, Int(0))
XCTAssertEqual(msg.repeatedEnumArray.count, UInt(0))
msg2.clear()
- XCTAssertEqual(msg2.optionalEnum, Message3_Enum.Foo) // Default
- XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Message3_Enum.Foo.rawValue)
+ XCTAssertEqual(msg2.optionalEnum, Message3_Enum.foo) // Default
+ XCTAssertEqual(Message3_OptionalEnum_RawValue(msg2), Message3_Enum.foo.rawValue)
XCTAssertEqual(msg.mapInt32Int32.count, UInt(0))
XCTAssertEqual(msg.mapStringString.count, Int(0))
XCTAssertEqual(msg.mapInt32Enum.count, UInt(0))
@@ -234,201 +234,201 @@ class GPBBridgeTests: XCTestCase {
// Access shouldn't result in has* but should return objects.
let msg2 = msg.optionalGroup
- let msg3 = msg.optionalMessage.optionalMessage
- let msg4 = msg.optionalMessage
+ let msg3 = msg.optional.optional
+ let msg4 = msg.optional
XCTAssertNotNil(msg2)
XCTAssertNotNil(msg3)
XCTAssertFalse(msg.hasOptionalGroup)
- XCTAssertFalse(msg.optionalMessage.hasOptionalMessage)
+ XCTAssertFalse(msg.optional.hasOptionalMessage)
XCTAssertFalse(msg.hasOptionalMessage)
// Setting things should trigger has* getting set.
msg.optionalGroup.a = 10
- msg.optionalMessage.optionalMessage.optionalInt32 = 100
+ msg.optional.optional.optionalInt32 = 100
XCTAssertTrue(msg.hasOptionalGroup)
- XCTAssertTrue(msg.optionalMessage.hasOptionalMessage)
+ XCTAssertTrue(msg.optional.hasOptionalMessage)
XCTAssertTrue(msg.hasOptionalMessage)
// And they should be the same pointer as before.
XCTAssertTrue(msg2 === msg.optionalGroup)
- XCTAssertTrue(msg3 === msg.optionalMessage.optionalMessage)
- XCTAssertTrue(msg4 === msg.optionalMessage)
+ XCTAssertTrue(msg3 === msg.optional.optional)
+ XCTAssertTrue(msg4 === msg.optional)
// Clear gets us new objects next time around.
msg.clear()
XCTAssertFalse(msg.hasOptionalGroup)
- XCTAssertFalse(msg.optionalMessage.hasOptionalMessage)
+ XCTAssertFalse(msg.optional.hasOptionalMessage)
XCTAssertFalse(msg.hasOptionalMessage)
msg.optionalGroup.a = 20
- msg.optionalMessage.optionalMessage.optionalInt32 = 200
+ msg.optional.optional.optionalInt32 = 200
XCTAssertTrue(msg.hasOptionalGroup)
- XCTAssertTrue(msg.optionalMessage.hasOptionalMessage)
+ XCTAssertTrue(msg.optional.hasOptionalMessage)
XCTAssertTrue(msg.hasOptionalMessage)
XCTAssertTrue(msg2 !== msg.optionalGroup)
- XCTAssertTrue(msg3 !== msg.optionalMessage.optionalMessage)
- XCTAssertTrue(msg4 !== msg.optionalMessage)
+ XCTAssertTrue(msg3 !== msg.optional.optional)
+ XCTAssertTrue(msg4 !== msg.optional)
// Explicit set of a message, means autocreated object doesn't bind.
msg.clear()
- let autoCreated = msg.optionalMessage
+ let autoCreated = msg.optional
XCTAssertFalse(msg.hasOptionalMessage)
let msg5 = Message2()
msg5.optionalInt32 = 123
- msg.optionalMessage = msg5
+ msg.optional = msg5
XCTAssertTrue(msg.hasOptionalMessage)
// Modifing the autocreated doesn't replaced the explicit set one.
- autoCreated.optionalInt32 = 456
+ autoCreated?.optionalInt32 = 456
XCTAssertTrue(msg.hasOptionalMessage)
- XCTAssertTrue(msg.optionalMessage === msg5)
- XCTAssertEqual(msg.optionalMessage.optionalInt32, Int32(123))
+ XCTAssertTrue(msg.optional === msg5)
+ XCTAssertEqual(msg.optional.optionalInt32, Int32(123))
}
func testProto2OneOfSupport() {
let msg = Message2()
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default
XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message2_Enum.Baz) // Default
- let autoCreated = msg.oneofMessage // Default create one.
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default
+ let autoCreated = msg.oneof // Default create one.
XCTAssertNotNil(autoCreated)
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
msg.oneofInt32 = 10
XCTAssertEqual(msg.oneofInt32, Int32(10))
XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message2_Enum.Baz) // Default
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.OneofInt32)
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofInt32)
msg.oneofFloat = 20.0
XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default
XCTAssertEqual(msg.oneofFloat, Float(20.0))
- XCTAssertEqual(msg.oneofEnum, Message2_Enum.Baz) // Default
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.OneofFloat)
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofFloat)
- msg.oneofEnum = .Bar
+ msg.oneofEnum = .bar
XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default
XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message2_Enum.Bar)
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.OneofEnum)
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum.bar)
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofEnum)
// Sets via the autocreated instance.
- msg.oneofMessage.optionalInt32 = 200
+ msg.oneof.optionalInt32 = 200
XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default
XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message2_Enum.Baz) // Default
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(200))
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.OneofMessage)
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(200))
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofMessage)
// Clear the oneof.
Message2_ClearOOneOfCase(msg)
XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default
XCTAssertEqual(msg.oneofFloat, Float(110.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message2_Enum.Baz) // Default
- let autoCreated2 = msg.oneofMessage // Default create one
+ XCTAssertEqual(msg.oneofEnum, Message2_Enum.baz) // Default
+ let autoCreated2 = msg.oneof // Default create one
XCTAssertNotNil(autoCreated2)
XCTAssertTrue(autoCreated2 !== autoCreated) // New instance
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(0)) // Default
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
msg.oneofInt32 = 10
XCTAssertEqual(msg.oneofInt32, Int32(10))
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.OneofInt32)
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofInt32)
// Confirm Message.clear() handles the oneof correctly.
msg.clear()
XCTAssertEqual(msg.oneofInt32, Int32(100)) // Default
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
// Sets via the autocreated instance.
- msg.oneofMessage.optionalInt32 = 300
- XCTAssertTrue(msg.oneofMessage !== autoCreated) // New instance
- XCTAssertTrue(msg.oneofMessage !== autoCreated2) // New instance
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(300))
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.OneofMessage)
+ msg.oneof.optionalInt32 = 300
+ XCTAssertTrue(msg.oneof !== autoCreated) // New instance
+ XCTAssertTrue(msg.oneof !== autoCreated2) // New instance
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(300))
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.oneofMessage)
// Set message to nil clears the oneof.
- msg.oneofMessage = nil
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(0)) // Default
- XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.GPBUnsetOneOfCase)
+ msg.oneof = nil
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default
+ XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase.gpbUnsetOneOfCase)
}
func testProto3OneOfSupport() {
let msg = Message3()
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default
XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message3_Enum.Foo) // Default
- let autoCreated = msg.oneofMessage // Default create one.
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default
+ let autoCreated = msg.oneof // Default create one.
XCTAssertNotNil(autoCreated)
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
msg.oneofInt32 = 10
XCTAssertEqual(msg.oneofInt32, Int32(10))
XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message3_Enum.Foo) // Default
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.OneofInt32)
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofInt32)
msg.oneofFloat = 20.0
XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default
XCTAssertEqual(msg.oneofFloat, Float(20.0))
- XCTAssertEqual(msg.oneofEnum, Message3_Enum.Foo) // Default
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.OneofFloat)
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofFloat)
- msg.oneofEnum = .Bar
+ msg.oneofEnum = .bar
XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default
XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message3_Enum.Bar)
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.OneofEnum)
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum.bar)
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofEnum)
// Sets via the autocreated instance.
- msg.oneofMessage.optionalInt32 = 200
+ msg.oneof.optionalInt32 = 200
XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default
XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message3_Enum.Foo) // Default
- XCTAssertTrue(msg.oneofMessage === autoCreated) // Still the same
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(200))
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.OneofMessage)
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default
+ XCTAssertTrue(msg.oneof === autoCreated) // Still the same
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(200))
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofMessage)
// Clear the oneof.
Message3_ClearOOneOfCase(msg)
XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default
XCTAssertEqual(msg.oneofFloat, Float(0.0)) // Default
- XCTAssertEqual(msg.oneofEnum, Message3_Enum.Foo) // Default
- let autoCreated2 = msg.oneofMessage // Default create one
+ XCTAssertEqual(msg.oneofEnum, Message3_Enum.foo) // Default
+ let autoCreated2 = msg.oneof // Default create one
XCTAssertNotNil(autoCreated2)
XCTAssertTrue(autoCreated2 !== autoCreated) // New instance
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(0)) // Default
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
msg.oneofInt32 = 10
XCTAssertEqual(msg.oneofInt32, Int32(10))
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.OneofInt32)
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofInt32)
// Confirm Message.clear() handles the oneof correctly.
msg.clear()
XCTAssertEqual(msg.oneofInt32, Int32(0)) // Default
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.GPBUnsetOneOfCase)
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
// Sets via the autocreated instance.
- msg.oneofMessage.optionalInt32 = 300
- XCTAssertTrue(msg.oneofMessage !== autoCreated) // New instance
- XCTAssertTrue(msg.oneofMessage !== autoCreated2) // New instance
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(300))
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.OneofMessage)
+ msg.oneof.optionalInt32 = 300
+ XCTAssertTrue(msg.oneof !== autoCreated) // New instance
+ XCTAssertTrue(msg.oneof !== autoCreated2) // New instance
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(300))
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.oneofMessage)
// Set message to nil clears the oneof.
- msg.oneofMessage = nil
- XCTAssertEqual(msg.oneofMessage.optionalInt32, Int32(0)) // Default
- XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.GPBUnsetOneOfCase)
+ msg.oneof = nil
+ XCTAssertEqual(msg.oneof.optionalInt32, Int32(0)) // Default
+ XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase.gpbUnsetOneOfCase)
}
func testSerialization() {
@@ -437,12 +437,12 @@ class GPBBridgeTests: XCTestCase {
msg.optionalInt32 = 100
msg.optionalInt64 = 101
msg.optionalGroup.a = 102
- msg.repeatedStringArray.addObject("abc")
- msg.repeatedStringArray.addObject("def")
+ msg.repeatedStringArray.add("abc")
+ msg.repeatedStringArray.add("def")
msg.mapInt32Int32.setInt32(200, forKey:300)
msg.mapInt32Int32.setInt32(201, forKey:201)
- msg.mapStringString.setObject("foo", forKey:"bar")
- msg.mapStringString.setObject("abc", forKey:"xyz")
+ msg.mapStringString.setObject("foo", forKey:"bar" as NSString)
+ msg.mapStringString.setObject("abc", forKey:"xyz" as NSString)
let data = msg.data()
diff --git a/objectivec/Tests/GPBUnittestProtos.m b/objectivec/Tests/GPBUnittestProtos.m
index d19beee9..8d2948bf 100644
--- a/objectivec/Tests/GPBUnittestProtos.m
+++ b/objectivec/Tests/GPBUnittestProtos.m
@@ -36,6 +36,7 @@
// a descriptor as it doesn't use the classes/enums.
#import "google/protobuf/Descriptor.pbobjc.m"
+#import "google/protobuf/AnyTest.pbobjc.m"
#import "google/protobuf/MapProto2Unittest.pbobjc.m"
#import "google/protobuf/MapUnittest.pbobjc.m"
#import "google/protobuf/Unittest.pbobjc.m"
@@ -62,3 +63,11 @@
#import "google/protobuf/UnittestPreserveUnknownEnum.pbobjc.m"
#import "google/protobuf/UnittestRuntimeProto2.pbobjc.m"
#import "google/protobuf/UnittestRuntimeProto3.pbobjc.m"
+
+#import "google/protobuf/UnittestExtensionChainA.pbobjc.m"
+#import "google/protobuf/UnittestExtensionChainB.pbobjc.m"
+#import "google/protobuf/UnittestExtensionChainC.pbobjc.m"
+#import "google/protobuf/UnittestExtensionChainD.pbobjc.m"
+#import "google/protobuf/UnittestExtensionChainE.pbobjc.m"
+// See GPBUnittestProtos2.m for for "UnittestExtensionChainF.pbobjc.m"
+#import "google/protobuf/UnittestExtensionChainG.pbobjc.m"
diff --git a/objectivec/Tests/GPBUnittestProtos2.m b/objectivec/Tests/GPBUnittestProtos2.m
new file mode 100644
index 00000000..ef9f0702
--- /dev/null
+++ b/objectivec/Tests/GPBUnittestProtos2.m
@@ -0,0 +1,34 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// This one file in the chain tests is compiled by itself to ensure if was
+// generated with the extra #imports needed to pull in the indirect Root class
+// used in its Root registry.
+#import "google/protobuf/UnittestExtensionChainF.pbobjc.m"
diff --git a/objectivec/Tests/GPBWellKnownTypesTest.m b/objectivec/Tests/GPBWellKnownTypesTest.m
index 78f4e637..041841dd 100644
--- a/objectivec/Tests/GPBWellKnownTypesTest.m
+++ b/objectivec/Tests/GPBWellKnownTypesTest.m
@@ -32,6 +32,8 @@
#import <XCTest/XCTest.h>
+#import "google/protobuf/AnyTest.pbobjc.h"
+
// A basically random interval into the future for testing with.
static const NSTimeInterval kFutureOffsetInterval = 15000;
@@ -99,4 +101,58 @@ static const NSTimeInterval kTimeAccuracy = 1e-9;
[duration2 release];
}
+- (void)testAnyHelpers {
+
+ // Set and extract covers most of the code.
+
+ TestAny *subMessage = [TestAny message];
+ subMessage.int32Value = 12345;
+ TestAny *message = [TestAny message];
+ NSError *err = nil;
+ message.anyValue = [GPBAny anyWithMessage:subMessage error:&err];
+ XCTAssertNil(err);
+
+ NSData *data = message.data;
+ XCTAssertNotNil(data);
+
+ TestAny *message2 = [TestAny parseFromData:data error:&err];
+ XCTAssertNil(err);
+ XCTAssertNotNil(message2);
+ XCTAssertTrue(message2.hasAnyValue);
+
+ TestAny *subMessage2 =
+ (TestAny *)[message.anyValue unpackMessageClass:[TestAny class]
+ error:&err];
+ XCTAssertNil(err);
+ XCTAssertNotNil(subMessage2);
+ XCTAssertEqual(subMessage2.int32Value, 12345);
+
+ // NULL errorPtr in the two calls.
+
+ message.anyValue = [GPBAny anyWithMessage:subMessage error:NULL];
+ NSData *data2 = message.data;
+ XCTAssertEqualObjects(data2, data);
+
+ TestAny *subMessage3 =
+ (TestAny *)[message.anyValue unpackMessageClass:[TestAny class]
+ error:NULL];
+ XCTAssertNotNil(subMessage3);
+ XCTAssertEqualObjects(subMessage2, subMessage3);
+
+ // Try to extract wrong type.
+
+ GPBTimestamp *wrongMessage =
+ (GPBTimestamp *)[message.anyValue unpackMessageClass:[GPBTimestamp class]
+ error:&err];
+ XCTAssertNotNil(err);
+ XCTAssertNil(wrongMessage);
+ XCTAssertEqualObjects(err.domain, GPBWellKnownTypesErrorDomain);
+ XCTAssertEqual(err.code, GPBWellKnownTypesErrorCodeTypeURLMismatch);
+
+ wrongMessage =
+ (GPBTimestamp *)[message.anyValue unpackMessageClass:[GPBTimestamp class]
+ error:NULL];
+ XCTAssertNil(wrongMessage);
+}
+
@end
diff --git a/objectivec/Tests/unittest_cycle.proto b/objectivec/Tests/unittest_cycle.proto
index 5f6f56a1..afc1b0fe 100644
--- a/objectivec/Tests/unittest_cycle.proto
+++ b/objectivec/Tests/unittest_cycle.proto
@@ -31,10 +31,8 @@ syntax = "proto2";
package protobuf_unittest;
-// Cycles in the Message graph can cause problems for the mutable classes
-// since the properties on the mutable class change types. This file just
-// needs to generate source, and that source must compile, to ensure the
-// generated source works for this sort of case.
+// Cycles in the Message graph can cause problems for message class
+// initialization order.
// You can't make a object graph that spans files, so this can only be done
// within a single proto file.
diff --git a/objectivec/Tests/unittest_extension_chain_a.proto b/objectivec/Tests/unittest_extension_chain_a.proto
new file mode 100644
index 00000000..6a227eb9
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_a.proto
@@ -0,0 +1,51 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "google/protobuf/unittest.proto";
+
+import "unittest_extension_chain_b.proto";
+import "unittest_extension_chain_c.proto";
+import "unittest_extension_chain_d.proto";
+
+// The Root for this file should end up adding the local extension and merging
+// in the extensions from D's Root (unittest and C will come via D's).
+
+message ChainAMessage {
+ optional ChainBMessage b = 1;
+ optional ChainCMessage c = 2;
+ optional ChainDMessage d = 3;
+}
+
+extend TestAllExtensions {
+ optional int32 chain_a_extension = 10001;
+}
diff --git a/objectivec/Tests/unittest_extension_chain_b.proto b/objectivec/Tests/unittest_extension_chain_b.proto
new file mode 100644
index 00000000..0da7ed3e
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_b.proto
@@ -0,0 +1,47 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "google/protobuf/unittest.proto";
+
+import "unittest_extension_chain_c.proto";
+
+// The Root for this file should end up adding the local extension and merging
+// in the extensions from C's Root (unittest will come via C's).
+
+message ChainBMessage {
+ optional ChainCMessage c = 1;
+}
+
+extend TestAllExtensions {
+ optional int32 chain_b_extension = 10002;
+}
diff --git a/objectivec/Tests/unittest_extension_chain_c.proto b/objectivec/Tests/unittest_extension_chain_c.proto
new file mode 100644
index 00000000..c702900a
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_c.proto
@@ -0,0 +1,45 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "google/protobuf/unittest.proto";
+
+// The Root for this file should end up adding the local extension and merging
+// in the extensions from unittest.proto's Root.
+
+message ChainCMessage {
+ optional int32 my_field = 1;
+}
+
+extend TestAllExtensions {
+ optional int32 chain_c_extension = 10003;
+}
diff --git a/objectivec/Tests/unittest_extension_chain_d.proto b/objectivec/Tests/unittest_extension_chain_d.proto
new file mode 100644
index 00000000..f9abe3ba
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_d.proto
@@ -0,0 +1,49 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "google/protobuf/unittest.proto";
+
+import "unittest_extension_chain_b.proto";
+import "unittest_extension_chain_c.proto";
+
+// The root should end up needing to merge B (C will be merged into B, so it
+// doesn't need to be directly merged).
+
+message ChainDMessage {
+ optional ChainBMessage b = 1;
+ optional ChainCMessage c = 2;
+}
+
+extend TestAllExtensions {
+ optional int32 chain_d_extension = 10004;
+}
diff --git a/objectivec/Tests/unittest_extension_chain_e.proto b/objectivec/Tests/unittest_extension_chain_e.proto
new file mode 100644
index 00000000..fe116631
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_e.proto
@@ -0,0 +1,40 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "google/protobuf/unittest.proto";
+
+// The Root for this file should end up just merging in unittest's Root.
+
+message ChainEMessage {
+ optional TestAllTypes my_field = 1;
+}
diff --git a/objectivec/Tests/unittest_extension_chain_f.proto b/objectivec/Tests/unittest_extension_chain_f.proto
new file mode 100644
index 00000000..b9bed723
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_f.proto
@@ -0,0 +1,44 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "unittest_extension_chain_g.proto";
+
+// The Root for this file should just be merging in the extensions from C's
+// Root (because G doens't define anything itself).
+
+// The generated source will also have to directly import C's .h file so it can
+// compile the reference to C's Root class.
+
+message ChainFMessage {
+ optional ChainGMessage g = 1;
+}
diff --git a/objectivec/Tests/unittest_extension_chain_g.proto b/objectivec/Tests/unittest_extension_chain_g.proto
new file mode 100644
index 00000000..aee827b1
--- /dev/null
+++ b/objectivec/Tests/unittest_extension_chain_g.proto
@@ -0,0 +1,41 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2016 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.
+
+syntax = "proto2";
+
+package protobuf_unittest;
+
+import "unittest_extension_chain_c.proto";
+
+// The Root for this file should just be merging in the extensions from C's
+// Root.
+
+message ChainGMessage {
+ optional ChainCMessage c = 1;
+}
diff --git a/objectivec/Tests/unittest_objc.proto b/objectivec/Tests/unittest_objc.proto
index 914945eb..e5577faf 100644
--- a/objectivec/Tests/unittest_objc.proto
+++ b/objectivec/Tests/unittest_objc.proto
@@ -34,6 +34,15 @@ import "google/protobuf/unittest.proto";
package protobuf_unittest;
+// Used to check that Headerdocs and appledoc work correctly. If these comments
+// are not handled correctly, Xcode will fail to build the tests.
+message TestGeneratedComments {
+ // This is a string that could contain stuff like
+ // mime types as image/* or */plain. Maybe twitter usernames
+ // like @protobuf, @google or @something.
+ optional string string_field = 1;
+}
+
// Using the messages in unittest.proto, setup for recursive cases for testing
// extensions at various depths.
extend TestAllExtensions {
diff --git a/objectivec/google/protobuf/Any.pbobjc.h b/objectivec/google/protobuf/Any.pbobjc.h
index 4253b604..d236e4b2 100644
--- a/objectivec/google/protobuf/Any.pbobjc.h
+++ b/objectivec/google/protobuf/Any.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,14 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBAnyRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBAnyRoot : GPBRootObject
@end
@@ -46,101 +51,105 @@ typedef GPB_ENUM(GPBAny_FieldNumber) {
GPBAny_FieldNumber_Value = 2,
};
-/// `Any` contains an arbitrary serialized protocol buffer message along with a
-/// URL that describes the type of the serialized message.
-///
-/// Protobuf library provides support to pack/unpack Any values in the form
-/// of utility functions or additional generated methods of the Any type.
-///
-/// Example 1: Pack and unpack a message in C++.
-///
-/// Foo foo = ...;
-/// Any any;
-/// any.PackFrom(foo);
-/// ...
-/// if (any.UnpackTo(&foo)) {
-/// ...
-/// }
-///
-/// Example 2: Pack and unpack a message in Java.
-///
-/// Foo foo = ...;
-/// Any any = Any.pack(foo);
-/// ...
-/// if (any.is(Foo.class)) {
-/// foo = any.unpack(Foo.class);
-/// }
-///
-/// Example 3: Pack and unpack a message in Python.
-///
-/// foo = Foo(...)
-/// any = Any()
-/// any.Pack(foo)
-/// ...
-/// if any.Is(Foo.DESCRIPTOR):
-/// any.Unpack(foo)
-/// ...
-///
-/// The pack methods provided by protobuf library will by default use
-/// 'type.googleapis.com/full.type.name' as the type URL and the unpack
-/// methods only use the fully qualified type name after the last '/'
-/// in the type URL, for example "foo.bar.com/x/y.z" will yield type
-/// name "y.z".
-///
-///
-/// JSON
-/// ====
-/// The JSON representation of an `Any` value uses the regular
-/// representation of the deserialized, embedded message, with an
-/// additional field `\@type` which contains the type URL. Example:
-///
-/// package google.profile;
-/// message Person {
-/// string first_name = 1;
-/// string last_name = 2;
-/// }
-///
-/// {
-/// "\@type": "type.googleapis.com/google.profile.Person",
-/// "firstName": <string>,
-/// "lastName": <string>
-/// }
-///
-/// If the embedded message type is well-known and has a custom JSON
-/// representation, that representation will be embedded adding a field
-/// `value` which holds the custom JSON in addition to the `\@type`
-/// field. Example (for message [google.protobuf.Duration][]):
-///
-/// {
-/// "\@type": "type.googleapis.com/google.protobuf.Duration",
-/// "value": "1.212s"
-/// }
+/**
+ * `Any` contains an arbitrary serialized protocol buffer message along with a
+ * URL that describes the type of the serialized message.
+ *
+ * Protobuf library provides support to pack/unpack Any values in the form
+ * of utility functions or additional generated methods of the Any type.
+ *
+ * Example 1: Pack and unpack a message in C++.
+ *
+ * Foo foo = ...;
+ * Any any;
+ * any.PackFrom(foo);
+ * ...
+ * if (any.UnpackTo(&foo)) {
+ * ...
+ * }
+ *
+ * Example 2: Pack and unpack a message in Java.
+ *
+ * Foo foo = ...;
+ * Any any = Any.pack(foo);
+ * ...
+ * if (any.is(Foo.class)) {
+ * foo = any.unpack(Foo.class);
+ * }
+ *
+ * Example 3: Pack and unpack a message in Python.
+ *
+ * foo = Foo(...)
+ * any = Any()
+ * any.Pack(foo)
+ * ...
+ * if any.Is(Foo.DESCRIPTOR):
+ * any.Unpack(foo)
+ * ...
+ *
+ * The pack methods provided by protobuf library will by default use
+ * 'type.googleapis.com/full.type.name' as the type URL and the unpack
+ * methods only use the fully qualified type name after the last '/'
+ * in the type URL, for example "foo.bar.com/x/y.z" will yield type
+ * name "y.z".
+ *
+ *
+ * JSON
+ * ====
+ * The JSON representation of an `Any` value uses the regular
+ * representation of the deserialized, embedded message, with an
+ * additional field `\@type` which contains the type URL. Example:
+ *
+ * package google.profile;
+ * message Person {
+ * string first_name = 1;
+ * string last_name = 2;
+ * }
+ *
+ * {
+ * "\@type": "type.googleapis.com/google.profile.Person",
+ * "firstName": <string>,
+ * "lastName": <string>
+ * }
+ *
+ * If the embedded message type is well-known and has a custom JSON
+ * representation, that representation will be embedded adding a field
+ * `value` which holds the custom JSON in addition to the `\@type`
+ * field. Example (for message [google.protobuf.Duration][]):
+ *
+ * {
+ * "\@type": "type.googleapis.com/google.protobuf.Duration",
+ * "value": "1.212s"
+ * }
+ **/
@interface GPBAny : GPBMessage
-/// A URL/resource name whose content describes the type of the
-/// serialized protocol buffer message.
-///
-/// For URLs which use the scheme `http`, `https`, or no scheme, the
-/// following restrictions and interpretations apply:
-///
-/// * If no scheme is provided, `https` is assumed.
-/// * The last segment of the URL's path must represent the fully
-/// qualified name of the type (as in `path/google.protobuf.Duration`).
-/// The name should be in a canonical form (e.g., leading "." is
-/// not accepted).
-/// * An HTTP GET on the URL must yield a [google.protobuf.Type][]
-/// value in binary format, or produce an error.
-/// * Applications are allowed to cache lookup results based on the
-/// URL, or have them precompiled into a binary to avoid any
-/// lookup. Therefore, binary compatibility needs to be preserved
-/// on changes to types. (Use versioned type names to manage
-/// breaking changes.)
-///
-/// Schemes other than `http`, `https` (or the empty scheme) might be
-/// used with implementation specific semantics.
+/**
+ * A URL/resource name whose content describes the type of the
+ * serialized protocol buffer message.
+ *
+ * For URLs which use the scheme `http`, `https`, or no scheme, the
+ * following restrictions and interpretations apply:
+ *
+ * * If no scheme is provided, `https` is assumed.
+ * * The last segment of the URL's path must represent the fully
+ * qualified name of the type (as in `path/google.protobuf.Duration`).
+ * The name should be in a canonical form (e.g., leading "." is
+ * not accepted).
+ * * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ * value in binary format, or produce an error.
+ * * Applications are allowed to cache lookup results based on the
+ * URL, or have them precompiled into a binary to avoid any
+ * lookup. Therefore, binary compatibility needs to be preserved
+ * on changes to types. (Use versioned type names to manage
+ * breaking changes.)
+ *
+ * Schemes other than `http`, `https` (or the empty scheme) might be
+ * used with implementation specific semantics.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL;
-/// Must be a valid serialized protocol buffer of the above specified type.
+/** Must be a valid serialized protocol buffer of the above specified type. */
@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
@end
diff --git a/objectivec/google/protobuf/Any.pbobjc.m b/objectivec/google/protobuf/Any.pbobjc.m
index 25e5b4c4..d210643f 100644
--- a/objectivec/google/protobuf/Any.pbobjc.m
+++ b/objectivec/google/protobuf/Any.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBAnyRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBAnyRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBAnyRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -68,7 +72,7 @@ typedef struct GPBAny__storage_ {
.number = GPBAny_FieldNumber_TypeURL,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBAny__storage_, typeURL),
- .flags = GPBFieldOptional | GPBFieldTextFormatNameCustom,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
.dataType = GPBDataTypeString,
},
{
@@ -88,7 +92,7 @@ typedef struct GPBAny__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBAny__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
static const char *extraTextFormatInfo =
"\001\001\004\241!!\000";
diff --git a/objectivec/google/protobuf/Api.pbobjc.h b/objectivec/google/protobuf/Api.pbobjc.h
index 04341f47..742a8122 100644
--- a/objectivec/google/protobuf/Api.pbobjc.h
+++ b/objectivec/google/protobuf/Api.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -34,14 +37,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBApiRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBApiRoot : GPBRootObject
@end
@@ -57,67 +62,79 @@ typedef GPB_ENUM(GPBApi_FieldNumber) {
GPBApi_FieldNumber_Syntax = 7,
};
-/// Api is a light-weight descriptor for a protocol buffer service.
+/**
+ * Api is a light-weight descriptor for a protocol buffer service.
+ **/
@interface GPBApi : GPBMessage
-/// The fully qualified name of this api, including package name
-/// followed by the api's simple name.
+/**
+ * The fully qualified name of this api, including package name
+ * followed by the api's simple name.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// The methods of this api, in unspecified order.
+/** The methods of this api, in unspecified order. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMethod*> *methodsArray;
-/// The number of items in @c methodsArray without causing the array to be created.
+/** The number of items in @c methodsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger methodsArray_Count;
-/// Any metadata attached to the API.
+/** Any metadata attached to the API. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/// The number of items in @c optionsArray without causing the array to be created.
+/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-/// A version string for this api. If specified, must have the form
-/// `major-version.minor-version`, as in `1.10`. If the minor version
-/// is omitted, it defaults to zero. If the entire version field is
-/// empty, the major version is derived from the package name, as
-/// outlined below. If the field is not empty, the version in the
-/// package name will be verified to be consistent with what is
-/// provided here.
-///
-/// The versioning schema uses [semantic
-/// versioning](http://semver.org) where the major version number
-/// indicates a breaking change and the minor version an additive,
-/// non-breaking change. Both version numbers are signals to users
-/// what to expect from different versions, and should be carefully
-/// chosen based on the product plan.
-///
-/// The major version is also reflected in the package name of the
-/// API, which must end in `v<major-version>`, as in
-/// `google.feature.v1`. For major versions 0 and 1, the suffix can
-/// be omitted. Zero major versions must only be used for
-/// experimental, none-GA apis.
+/**
+ * A version string for this api. If specified, must have the form
+ * `major-version.minor-version`, as in `1.10`. If the minor version
+ * is omitted, it defaults to zero. If the entire version field is
+ * empty, the major version is derived from the package name, as
+ * outlined below. If the field is not empty, the version in the
+ * package name will be verified to be consistent with what is
+ * provided here.
+ *
+ * The versioning schema uses [semantic
+ * versioning](http://semver.org) where the major version number
+ * indicates a breaking change and the minor version an additive,
+ * non-breaking change. Both version numbers are signals to users
+ * what to expect from different versions, and should be carefully
+ * chosen based on the product plan.
+ *
+ * The major version is also reflected in the package name of the
+ * API, which must end in `v<major-version>`, as in
+ * `google.feature.v1`. For major versions 0 and 1, the suffix can
+ * be omitted. Zero major versions must only be used for
+ * experimental, none-GA apis.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *version;
-/// Source context for the protocol buffer service represented by this
-/// message.
+/**
+ * Source context for the protocol buffer service represented by this
+ * message.
+ **/
@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
-/// Test to see if @c sourceContext has been set.
+/** Test to see if @c sourceContext has been set. */
@property(nonatomic, readwrite) BOOL hasSourceContext;
-/// Included APIs. See [Mixin][].
+/** Included APIs. See [Mixin][]. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBMixin*> *mixinsArray;
-/// The number of items in @c mixinsArray without causing the array to be created.
+/** The number of items in @c mixinsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger mixinsArray_Count;
-/// The source syntax of the service.
+/** The source syntax of the service. */
@property(nonatomic, readwrite) enum GPBSyntax syntax;
@end
-/// Fetches the raw value of a @c GPBApi's @c syntax property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBApi's @c syntax property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBApi_Syntax_RawValue(GPBApi *message);
-/// Sets the raw value of an @c GPBApi's @c syntax property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBApi's @c syntax property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBApi_Syntax_RawValue(GPBApi *message, int32_t value);
#pragma mark - GPBMethod
@@ -132,40 +149,46 @@ typedef GPB_ENUM(GPBMethod_FieldNumber) {
GPBMethod_FieldNumber_Syntax = 7,
};
-/// Method represents a method of an api.
+/**
+ * Method represents a method of an api.
+ **/
@interface GPBMethod : GPBMessage
-/// The simple name of this method.
+/** The simple name of this method. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// A URL of the input message type.
+/** A URL of the input message type. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *requestTypeURL;
-/// If true, the request is streamed.
+/** If true, the request is streamed. */
@property(nonatomic, readwrite) BOOL requestStreaming;
-/// The URL of the output message type.
+/** The URL of the output message type. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *responseTypeURL;
-/// If true, the response is streamed.
+/** If true, the response is streamed. */
@property(nonatomic, readwrite) BOOL responseStreaming;
-/// Any metadata attached to the method.
+/** Any metadata attached to the method. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/// The number of items in @c optionsArray without causing the array to be created.
+/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-/// The source syntax of this method.
+/** The source syntax of this method. */
@property(nonatomic, readwrite) enum GPBSyntax syntax;
@end
-/// Fetches the raw value of a @c GPBMethod's @c syntax property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBMethod's @c syntax property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBMethod_Syntax_RawValue(GPBMethod *message);
-/// Sets the raw value of an @c GPBMethod's @c syntax property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBMethod's @c syntax property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBMethod_Syntax_RawValue(GPBMethod *message, int32_t value);
#pragma mark - GPBMixin
@@ -175,90 +198,94 @@ typedef GPB_ENUM(GPBMixin_FieldNumber) {
GPBMixin_FieldNumber_Root = 2,
};
-/// Declares an API to be included in this API. The including API must
-/// redeclare all the methods from the included API, but documentation
-/// and options are inherited as follows:
-///
-/// - If after comment and whitespace stripping, the documentation
-/// string of the redeclared method is empty, it will be inherited
-/// from the original method.
-///
-/// - Each annotation belonging to the service config (http,
-/// visibility) which is not set in the redeclared method will be
-/// inherited.
-///
-/// - If an http annotation is inherited, the path pattern will be
-/// modified as follows. Any version prefix will be replaced by the
-/// version of the including API plus the [root][] path if specified.
-///
-/// Example of a simple mixin:
-///
-/// package google.acl.v1;
-/// service AccessControl {
-/// // Get the underlying ACL object.
-/// rpc GetAcl(GetAclRequest) returns (Acl) {
-/// option (google.api.http).get = "/v1/{resource=**}:getAcl";
-/// }
-/// }
-///
-/// package google.storage.v2;
-/// service Storage {
-/// rpc GetAcl(GetAclRequest) returns (Acl);
-///
-/// // Get a data record.
-/// rpc GetData(GetDataRequest) returns (Data) {
-/// option (google.api.http).get = "/v2/{resource=**}";
-/// }
-/// }
-///
-/// Example of a mixin configuration:
-///
-/// apis:
-/// - name: google.storage.v2.Storage
-/// mixins:
-/// - name: google.acl.v1.AccessControl
-///
-/// The mixin construct implies that all methods in `AccessControl` are
-/// also declared with same name and request/response types in
-/// `Storage`. A documentation generator or annotation processor will
-/// see the effective `Storage.GetAcl` method after inherting
-/// documentation and annotations as follows:
-///
-/// service Storage {
-/// // Get the underlying ACL object.
-/// rpc GetAcl(GetAclRequest) returns (Acl) {
-/// option (google.api.http).get = "/v2/{resource=**}:getAcl";
-/// }
-/// ...
-/// }
-///
-/// Note how the version in the path pattern changed from `v1` to `v2`.
-///
-/// If the `root` field in the mixin is specified, it should be a
-/// relative path under which inherited HTTP paths are placed. Example:
-///
-/// apis:
-/// - name: google.storage.v2.Storage
-/// mixins:
-/// - name: google.acl.v1.AccessControl
-/// root: acls
-///
-/// This implies the following inherited HTTP annotation:
-///
-/// service Storage {
-/// // Get the underlying ACL object.
-/// rpc GetAcl(GetAclRequest) returns (Acl) {
-/// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
-/// }
-/// ...
-/// }
+/**
+ * Declares an API to be included in this API. The including API must
+ * redeclare all the methods from the included API, but documentation
+ * and options are inherited as follows:
+ *
+ * - If after comment and whitespace stripping, the documentation
+ * string of the redeclared method is empty, it will be inherited
+ * from the original method.
+ *
+ * - Each annotation belonging to the service config (http,
+ * visibility) which is not set in the redeclared method will be
+ * inherited.
+ *
+ * - If an http annotation is inherited, the path pattern will be
+ * modified as follows. Any version prefix will be replaced by the
+ * version of the including API plus the [root][] path if specified.
+ *
+ * Example of a simple mixin:
+ *
+ * package google.acl.v1;
+ * service AccessControl {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v1/{resource=**}:getAcl";
+ * }
+ * }
+ *
+ * package google.storage.v2;
+ * service Storage {
+ * rpc GetAcl(GetAclRequest) returns (Acl);
+ *
+ * // Get a data record.
+ * rpc GetData(GetDataRequest) returns (Data) {
+ * option (google.api.http).get = "/v2/{resource=**}";
+ * }
+ * }
+ *
+ * Example of a mixin configuration:
+ *
+ * apis:
+ * - name: google.storage.v2.Storage
+ * mixins:
+ * - name: google.acl.v1.AccessControl
+ *
+ * The mixin construct implies that all methods in `AccessControl` are
+ * also declared with same name and request/response types in
+ * `Storage`. A documentation generator or annotation processor will
+ * see the effective `Storage.GetAcl` method after inherting
+ * documentation and annotations as follows:
+ *
+ * service Storage {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v2/{resource=**}:getAcl";
+ * }
+ * ...
+ * }
+ *
+ * Note how the version in the path pattern changed from `v1` to `v2`.
+ *
+ * If the `root` field in the mixin is specified, it should be a
+ * relative path under which inherited HTTP paths are placed. Example:
+ *
+ * apis:
+ * - name: google.storage.v2.Storage
+ * mixins:
+ * - name: google.acl.v1.AccessControl
+ * root: acls
+ *
+ * This implies the following inherited HTTP annotation:
+ *
+ * service Storage {
+ * // Get the underlying ACL object.
+ * rpc GetAcl(GetAclRequest) returns (Acl) {
+ * option (google.api.http).get = "/v2/acls/{resource=**}:getAcl";
+ * }
+ * ...
+ * }
+ **/
@interface GPBMixin : GPBMessage
-/// The fully qualified name of the API which is included.
+/** The fully qualified name of the API which is included. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// If non-empty specifies a path under which inherited HTTP paths
-/// are rooted.
+/**
+ * If non-empty specifies a path under which inherited HTTP paths
+ * are rooted.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *root;
@end
diff --git a/objectivec/google/protobuf/Api.pbobjc.m b/objectivec/google/protobuf/Api.pbobjc.m
index cd37edaa..58b47157 100644
--- a/objectivec/google/protobuf/Api.pbobjc.m
+++ b/objectivec/google/protobuf/Api.pbobjc.m
@@ -31,18 +31,8 @@
@implementation GPBApiRoot
-+ (GPBExtensionRegistry*)extensionRegistry {
- // This is called by +initialize so there is no need to worry
- // about thread safety and initialization of registry.
- static GPBExtensionRegistry* registry = nil;
- if (!registry) {
- GPBDebugCheckRuntimeVersion();
- registry = [[GPBExtensionRegistry alloc] init];
- [registry addExtensions:[GPBSourceContextRoot extensionRegistry]];
- [registry addExtensions:[GPBTypeRoot extensionRegistry]];
- }
- return registry;
-}
+// No extensions in the file and none of the imports (direct or indirect)
+// defined extensions, so no need to generate +extensionRegistry.
@end
@@ -53,8 +43,9 @@ static GPBFileDescriptor *GPBApiRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -149,7 +140,7 @@ typedef struct GPBApi__storage_ {
.number = GPBApi_FieldNumber_Syntax,
.hasIndex = 3,
.offset = (uint32_t)offsetof(GPBApi__storage_, syntax),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
};
@@ -160,7 +151,7 @@ typedef struct GPBApi__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBApi__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -223,7 +214,7 @@ typedef struct GPBMethod__storage_ {
.number = GPBMethod_FieldNumber_RequestTypeURL,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBMethod__storage_, requestTypeURL),
- .flags = GPBFieldOptional | GPBFieldTextFormatNameCustom,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
.dataType = GPBDataTypeString,
},
{
@@ -241,7 +232,7 @@ typedef struct GPBMethod__storage_ {
.number = GPBMethod_FieldNumber_ResponseTypeURL,
.hasIndex = 4,
.offset = (uint32_t)offsetof(GPBMethod__storage_, responseTypeURL),
- .flags = GPBFieldOptional | GPBFieldTextFormatNameCustom,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
.dataType = GPBDataTypeString,
},
{
@@ -268,7 +259,7 @@ typedef struct GPBMethod__storage_ {
.number = GPBMethod_FieldNumber_Syntax,
.hasIndex = 7,
.offset = (uint32_t)offsetof(GPBMethod__storage_, syntax),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
};
@@ -279,7 +270,7 @@ typedef struct GPBMethod__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBMethod__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
static const char *extraTextFormatInfo =
"\002\002\007\244\241!!\000\004\010\244\241!!\000";
@@ -350,7 +341,7 @@ typedef struct GPBMixin__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBMixin__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/Duration.pbobjc.h b/objectivec/google/protobuf/Duration.pbobjc.h
index 4c3173d3..e70138a0 100644
--- a/objectivec/google/protobuf/Duration.pbobjc.h
+++ b/objectivec/google/protobuf/Duration.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,14 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBDurationRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBDurationRoot : GPBRootObject
@end
@@ -46,58 +51,70 @@ typedef GPB_ENUM(GPBDuration_FieldNumber) {
GPBDuration_FieldNumber_Nanos = 2,
};
-/// A Duration represents a signed, fixed-length span of time represented
-/// as a count of seconds and fractions of seconds at nanosecond
-/// resolution. It is independent of any calendar and concepts like "day"
-/// or "month". It is related to Timestamp in that the difference between
-/// two Timestamp values is a Duration and it can be added or subtracted
-/// from a Timestamp. Range is approximately +-10,000 years.
-///
-/// Example 1: Compute Duration from two Timestamps in pseudo code.
-///
-/// Timestamp start = ...;
-/// Timestamp end = ...;
-/// Duration duration = ...;
-///
-/// duration.seconds = end.seconds - start.seconds;
-/// duration.nanos = end.nanos - start.nanos;
-///
-/// if (duration.seconds < 0 && duration.nanos > 0) {
-/// duration.seconds += 1;
-/// duration.nanos -= 1000000000;
-/// } else if (durations.seconds > 0 && duration.nanos < 0) {
-/// duration.seconds -= 1;
-/// duration.nanos += 1000000000;
-/// }
-///
-/// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
-///
-/// Timestamp start = ...;
-/// Duration duration = ...;
-/// Timestamp end = ...;
-///
-/// end.seconds = start.seconds + duration.seconds;
-/// end.nanos = start.nanos + duration.nanos;
-///
-/// if (end.nanos < 0) {
-/// end.seconds -= 1;
-/// end.nanos += 1000000000;
-/// } else if (end.nanos >= 1000000000) {
-/// end.seconds += 1;
-/// end.nanos -= 1000000000;
-/// }
+/**
+ * A Duration represents a signed, fixed-length span of time represented
+ * as a count of seconds and fractions of seconds at nanosecond
+ * resolution. It is independent of any calendar and concepts like "day"
+ * or "month". It is related to Timestamp in that the difference between
+ * two Timestamp values is a Duration and it can be added or subtracted
+ * from a Timestamp. Range is approximately +-10,000 years.
+ *
+ * Example 1: Compute Duration from two Timestamps in pseudo code.
+ *
+ * Timestamp start = ...;
+ * Timestamp end = ...;
+ * Duration duration = ...;
+ *
+ * duration.seconds = end.seconds - start.seconds;
+ * duration.nanos = end.nanos - start.nanos;
+ *
+ * if (duration.seconds < 0 && duration.nanos > 0) {
+ * duration.seconds += 1;
+ * duration.nanos -= 1000000000;
+ * } else if (durations.seconds > 0 && duration.nanos < 0) {
+ * duration.seconds -= 1;
+ * duration.nanos += 1000000000;
+ * }
+ *
+ * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+ *
+ * Timestamp start = ...;
+ * Duration duration = ...;
+ * Timestamp end = ...;
+ *
+ * end.seconds = start.seconds + duration.seconds;
+ * end.nanos = start.nanos + duration.nanos;
+ *
+ * if (end.nanos < 0) {
+ * end.seconds -= 1;
+ * end.nanos += 1000000000;
+ * } else if (end.nanos >= 1000000000) {
+ * end.seconds += 1;
+ * end.nanos -= 1000000000;
+ * }
+ *
+ * Example 3: Compute Duration from datetime.timedelta in Python.
+ *
+ * td = datetime.timedelta(days=3, minutes=10)
+ * duration = Duration()
+ * duration.FromTimedelta(td)
+ **/
@interface GPBDuration : GPBMessage
-/// Signed seconds of the span of time. Must be from -315,576,000,000
-/// to +315,576,000,000 inclusive.
+/**
+ * Signed seconds of the span of time. Must be from -315,576,000,000
+ * to +315,576,000,000 inclusive.
+ **/
@property(nonatomic, readwrite) int64_t seconds;
-/// Signed fractions of a second at nanosecond resolution of the span
-/// of time. Durations less than one second are represented with a 0
-/// `seconds` field and a positive or negative `nanos` field. For durations
-/// of one second or more, a non-zero value for the `nanos` field must be
-/// of the same sign as the `seconds` field. Must be from -999,999,999
-/// to +999,999,999 inclusive.
+/**
+ * Signed fractions of a second at nanosecond resolution of the span
+ * of time. Durations less than one second are represented with a 0
+ * `seconds` field and a positive or negative `nanos` field. For durations
+ * of one second or more, a non-zero value for the `nanos` field must be
+ * of the same sign as the `seconds` field. Must be from -999,999,999
+ * to +999,999,999 inclusive.
+ **/
@property(nonatomic, readwrite) int32_t nanos;
@end
diff --git a/objectivec/google/protobuf/Duration.pbobjc.m b/objectivec/google/protobuf/Duration.pbobjc.m
index 35daa3df..bafb64a0 100644
--- a/objectivec/google/protobuf/Duration.pbobjc.m
+++ b/objectivec/google/protobuf/Duration.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBDurationRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBDurationRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBDurationRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -88,7 +92,7 @@ typedef struct GPBDuration__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBDuration__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/Empty.pbobjc.h b/objectivec/google/protobuf/Empty.pbobjc.h
index 2d2a86bc..bd49cfdb 100644
--- a/objectivec/google/protobuf/Empty.pbobjc.h
+++ b/objectivec/google/protobuf/Empty.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,28 +31,32 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBEmptyRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBEmptyRoot : GPBRootObject
@end
#pragma mark - GPBEmpty
-/// A generic empty message that you can re-use to avoid defining duplicated
-/// empty messages in your APIs. A typical example is to use it as the request
-/// or the response type of an API method. For instance:
-///
-/// service Foo {
-/// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
-/// }
-///
-/// The JSON representation for `Empty` is empty JSON object `{}`.
+/**
+ * A generic empty message that you can re-use to avoid defining duplicated
+ * empty messages in your APIs. A typical example is to use it as the request
+ * or the response type of an API method. For instance:
+ *
+ * service Foo {
+ * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+ * }
+ *
+ * The JSON representation for `Empty` is empty JSON object `{}`.
+ **/
@interface GPBEmpty : GPBMessage
@end
diff --git a/objectivec/google/protobuf/Empty.pbobjc.m b/objectivec/google/protobuf/Empty.pbobjc.m
index 1bdd4949..506b500e 100644
--- a/objectivec/google/protobuf/Empty.pbobjc.m
+++ b/objectivec/google/protobuf/Empty.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBEmptyRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBEmptyRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBEmptyRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -64,7 +68,7 @@ typedef struct GPBEmpty__storage_ {
fields:NULL
fieldCount:0
storageSize:sizeof(GPBEmpty__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.h b/objectivec/google/protobuf/FieldMask.pbobjc.h
index 06053f1a..07e60818 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.h
+++ b/objectivec/google/protobuf/FieldMask.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,14 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBFieldMaskRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBFieldMaskRoot : GPBRootObject
@end
@@ -45,212 +50,214 @@ typedef GPB_ENUM(GPBFieldMask_FieldNumber) {
GPBFieldMask_FieldNumber_PathsArray = 1,
};
-/// `FieldMask` represents a set of symbolic field paths, for example:
-///
-/// paths: "f.a"
-/// paths: "f.b.d"
-///
-/// Here `f` represents a field in some root message, `a` and `b`
-/// fields in the message found in `f`, and `d` a field found in the
-/// message in `f.b`.
-///
-/// Field masks are used to specify a subset of fields that should be
-/// returned by a get operation or modified by an update operation.
-/// Field masks also have a custom JSON encoding (see below).
-///
-/// # Field Masks in Projections
-///
-/// When used in the context of a projection, a response message or
-/// sub-message is filtered by the API to only contain those fields as
-/// specified in the mask. For example, if the mask in the previous
-/// example is applied to a response message as follows:
-///
-/// f {
-/// a : 22
-/// b {
-/// d : 1
-/// x : 2
-/// }
-/// y : 13
-/// }
-/// z: 8
-///
-/// The result will not contain specific values for fields x,y and z
-/// (their value will be set to the default, and omitted in proto text
-/// output):
-///
-///
-/// f {
-/// a : 22
-/// b {
-/// d : 1
-/// }
-/// }
-///
-/// A repeated field is not allowed except at the last position of a
-/// field mask.
-///
-/// If a FieldMask object is not present in a get operation, the
-/// operation applies to all fields (as if a FieldMask of all fields
-/// had been specified).
-///
-/// Note that a field mask does not necessarily apply to the
-/// top-level response message. In case of a REST get operation, the
-/// field mask applies directly to the response, but in case of a REST
-/// list operation, the mask instead applies to each individual message
-/// in the returned resource list. In case of a REST custom method,
-/// other definitions may be used. Where the mask applies will be
-/// clearly documented together with its declaration in the API. In
-/// any case, the effect on the returned resource/resources is required
-/// behavior for APIs.
-///
-/// # Field Masks in Update Operations
-///
-/// A field mask in update operations specifies which fields of the
-/// targeted resource are going to be updated. The API is required
-/// to only change the values of the fields as specified in the mask
-/// and leave the others untouched. If a resource is passed in to
-/// describe the updated values, the API ignores the values of all
-/// fields not covered by the mask.
-///
-/// If a repeated field is specified for an update operation, the existing
-/// repeated values in the target resource will be overwritten by the new values.
-/// Note that a repeated field is only allowed in the last position of a field
-/// mask.
-///
-/// If a sub-message is specified in the last position of the field mask for an
-/// update operation, then the existing sub-message in the target resource is
-/// overwritten. Given the target message:
-///
-/// f {
-/// b {
-/// d : 1
-/// x : 2
-/// }
-/// c : 1
-/// }
-///
-/// And an update message:
-///
-/// f {
-/// b {
-/// d : 10
-/// }
-/// }
-///
-/// then if the field mask is:
-///
-/// paths: "f.b"
-///
-/// then the result will be:
-///
-/// f {
-/// b {
-/// d : 10
-/// }
-/// c : 1
-/// }
-///
-/// However, if the update mask was:
-///
-/// paths: "f.b.d"
-///
-/// then the result would be:
-///
-/// f {
-/// b {
-/// d : 10
-/// x : 2
-/// }
-/// c : 1
-/// }
-///
-/// In order to reset a field's value to the default, the field must
-/// be in the mask and set to the default value in the provided resource.
-/// Hence, in order to reset all fields of a resource, provide a default
-/// instance of the resource and set all fields in the mask, or do
-/// not provide a mask as described below.
-///
-/// If a field mask is not present on update, the operation applies to
-/// all fields (as if a field mask of all fields has been specified).
-/// Note that in the presence of schema evolution, this may mean that
-/// fields the client does not know and has therefore not filled into
-/// the request will be reset to their default. If this is unwanted
-/// behavior, a specific service may require a client to always specify
-/// a field mask, producing an error if not.
-///
-/// As with get operations, the location of the resource which
-/// describes the updated values in the request message depends on the
-/// operation kind. In any case, the effect of the field mask is
-/// required to be honored by the API.
-///
-/// ## Considerations for HTTP REST
-///
-/// The HTTP kind of an update operation which uses a field mask must
-/// be set to PATCH instead of PUT in order to satisfy HTTP semantics
-/// (PUT must only be used for full updates).
-///
-/// # JSON Encoding of Field Masks
-///
-/// In JSON, a field mask is encoded as a single string where paths are
-/// separated by a comma. Fields name in each path are converted
-/// to/from lower-camel naming conventions.
-///
-/// As an example, consider the following message declarations:
-///
-/// message Profile {
-/// User user = 1;
-/// Photo photo = 2;
-/// }
-/// message User {
-/// string display_name = 1;
-/// string address = 2;
-/// }
-///
-/// In proto a field mask for `Profile` may look as such:
-///
-/// mask {
-/// paths: "user.display_name"
-/// paths: "photo"
-/// }
-///
-/// In JSON, the same mask is represented as below:
-///
-/// {
-/// mask: "user.displayName,photo"
-/// }
-///
-/// # Field Masks and Oneof Fields
-///
-/// Field masks treat fields in oneofs just as regular fields. Consider the
-/// following message:
-///
-/// message SampleMessage {
-/// oneof test_oneof {
-/// string name = 4;
-/// SubMessage sub_message = 9;
-/// }
-/// }
-///
-/// The field mask can be:
-///
-/// mask {
-/// paths: "name"
-/// }
-///
-/// Or:
-///
-/// mask {
-/// paths: "sub_message"
-/// }
-///
-/// Note that oneof type names ("test_oneof" in this case) cannot be used in
-/// paths.
+/**
+ * `FieldMask` represents a set of symbolic field paths, for example:
+ *
+ * paths: "f.a"
+ * paths: "f.b.d"
+ *
+ * Here `f` represents a field in some root message, `a` and `b`
+ * fields in the message found in `f`, and `d` a field found in the
+ * message in `f.b`.
+ *
+ * Field masks are used to specify a subset of fields that should be
+ * returned by a get operation or modified by an update operation.
+ * Field masks also have a custom JSON encoding (see below).
+ *
+ * # Field Masks in Projections
+ *
+ * When used in the context of a projection, a response message or
+ * sub-message is filtered by the API to only contain those fields as
+ * specified in the mask. For example, if the mask in the previous
+ * example is applied to a response message as follows:
+ *
+ * f {
+ * a : 22
+ * b {
+ * d : 1
+ * x : 2
+ * }
+ * y : 13
+ * }
+ * z: 8
+ *
+ * The result will not contain specific values for fields x,y and z
+ * (their value will be set to the default, and omitted in proto text
+ * output):
+ *
+ *
+ * f {
+ * a : 22
+ * b {
+ * d : 1
+ * }
+ * }
+ *
+ * A repeated field is not allowed except at the last position of a
+ * paths string.
+ *
+ * If a FieldMask object is not present in a get operation, the
+ * operation applies to all fields (as if a FieldMask of all fields
+ * had been specified).
+ *
+ * Note that a field mask does not necessarily apply to the
+ * top-level response message. In case of a REST get operation, the
+ * field mask applies directly to the response, but in case of a REST
+ * list operation, the mask instead applies to each individual message
+ * in the returned resource list. In case of a REST custom method,
+ * other definitions may be used. Where the mask applies will be
+ * clearly documented together with its declaration in the API. In
+ * any case, the effect on the returned resource/resources is required
+ * behavior for APIs.
+ *
+ * # Field Masks in Update Operations
+ *
+ * A field mask in update operations specifies which fields of the
+ * targeted resource are going to be updated. The API is required
+ * to only change the values of the fields as specified in the mask
+ * and leave the others untouched. If a resource is passed in to
+ * describe the updated values, the API ignores the values of all
+ * fields not covered by the mask.
+ *
+ * If a repeated field is specified for an update operation, the existing
+ * repeated values in the target resource will be overwritten by the new values.
+ * Note that a repeated field is only allowed in the last position of a `paths`
+ * string.
+ *
+ * If a sub-message is specified in the last position of the field mask for an
+ * update operation, then the existing sub-message in the target resource is
+ * overwritten. Given the target message:
+ *
+ * f {
+ * b {
+ * d : 1
+ * x : 2
+ * }
+ * c : 1
+ * }
+ *
+ * And an update message:
+ *
+ * f {
+ * b {
+ * d : 10
+ * }
+ * }
+ *
+ * then if the field mask is:
+ *
+ * paths: "f.b"
+ *
+ * then the result will be:
+ *
+ * f {
+ * b {
+ * d : 10
+ * }
+ * c : 1
+ * }
+ *
+ * However, if the update mask was:
+ *
+ * paths: "f.b.d"
+ *
+ * then the result would be:
+ *
+ * f {
+ * b {
+ * d : 10
+ * x : 2
+ * }
+ * c : 1
+ * }
+ *
+ * In order to reset a field's value to the default, the field must
+ * be in the mask and set to the default value in the provided resource.
+ * Hence, in order to reset all fields of a resource, provide a default
+ * instance of the resource and set all fields in the mask, or do
+ * not provide a mask as described below.
+ *
+ * If a field mask is not present on update, the operation applies to
+ * all fields (as if a field mask of all fields has been specified).
+ * Note that in the presence of schema evolution, this may mean that
+ * fields the client does not know and has therefore not filled into
+ * the request will be reset to their default. If this is unwanted
+ * behavior, a specific service may require a client to always specify
+ * a field mask, producing an error if not.
+ *
+ * As with get operations, the location of the resource which
+ * describes the updated values in the request message depends on the
+ * operation kind. In any case, the effect of the field mask is
+ * required to be honored by the API.
+ *
+ * ## Considerations for HTTP REST
+ *
+ * The HTTP kind of an update operation which uses a field mask must
+ * be set to PATCH instead of PUT in order to satisfy HTTP semantics
+ * (PUT must only be used for full updates).
+ *
+ * # JSON Encoding of Field Masks
+ *
+ * In JSON, a field mask is encoded as a single string where paths are
+ * separated by a comma. Fields name in each path are converted
+ * to/from lower-camel naming conventions.
+ *
+ * As an example, consider the following message declarations:
+ *
+ * message Profile {
+ * User user = 1;
+ * Photo photo = 2;
+ * }
+ * message User {
+ * string display_name = 1;
+ * string address = 2;
+ * }
+ *
+ * In proto a field mask for `Profile` may look as such:
+ *
+ * mask {
+ * paths: "user.display_name"
+ * paths: "photo"
+ * }
+ *
+ * In JSON, the same mask is represented as below:
+ *
+ * {
+ * mask: "user.displayName,photo"
+ * }
+ *
+ * # Field Masks and Oneof Fields
+ *
+ * Field masks treat fields in oneofs just as regular fields. Consider the
+ * following message:
+ *
+ * message SampleMessage {
+ * oneof test_oneof {
+ * string name = 4;
+ * SubMessage sub_message = 9;
+ * }
+ * }
+ *
+ * The field mask can be:
+ *
+ * mask {
+ * paths: "name"
+ * }
+ *
+ * Or:
+ *
+ * mask {
+ * paths: "sub_message"
+ * }
+ *
+ * Note that oneof type names ("test_oneof" in this case) cannot be used in
+ * paths.
+ **/
@interface GPBFieldMask : GPBMessage
-/// The set of field mask paths.
+/** The set of field mask paths. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<NSString*> *pathsArray;
-/// The number of items in @c pathsArray without causing the array to be created.
+/** The number of items in @c pathsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger pathsArray_Count;
@end
diff --git a/objectivec/google/protobuf/FieldMask.pbobjc.m b/objectivec/google/protobuf/FieldMask.pbobjc.m
index 2721fdfa..b0915af4 100644
--- a/objectivec/google/protobuf/FieldMask.pbobjc.m
+++ b/objectivec/google/protobuf/FieldMask.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBFieldMaskRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBFieldMaskRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBFieldMaskRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -77,7 +81,7 @@ typedef struct GPBFieldMask__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBFieldMask__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/SourceContext.pbobjc.h b/objectivec/google/protobuf/SourceContext.pbobjc.h
index 4514fa9f..799d190a 100644
--- a/objectivec/google/protobuf/SourceContext.pbobjc.h
+++ b/objectivec/google/protobuf/SourceContext.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,14 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBSourceContextRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBSourceContextRoot : GPBRootObject
@end
@@ -45,12 +50,16 @@ typedef GPB_ENUM(GPBSourceContext_FieldNumber) {
GPBSourceContext_FieldNumber_FileName = 1,
};
-/// `SourceContext` represents information about the source of a
-/// protobuf element, like the file in which it is defined.
+/**
+ * `SourceContext` represents information about the source of a
+ * protobuf element, like the file in which it is defined.
+ **/
@interface GPBSourceContext : GPBMessage
-/// The path-qualified name of the .proto file that contained the associated
-/// protobuf element. For example: `"google/protobuf/source_context.proto"`.
+/**
+ * The path-qualified name of the .proto file that contained the associated
+ * protobuf element. For example: `"google/protobuf/source_context.proto"`.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *fileName;
@end
diff --git a/objectivec/google/protobuf/SourceContext.pbobjc.m b/objectivec/google/protobuf/SourceContext.pbobjc.m
index 6e3c9c07..83bfa346 100644
--- a/objectivec/google/protobuf/SourceContext.pbobjc.m
+++ b/objectivec/google/protobuf/SourceContext.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBSourceContextRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBSourceContextRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBSourceContextRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -77,7 +81,7 @@ typedef struct GPBSourceContext__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBSourceContext__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/Struct.pbobjc.h b/objectivec/google/protobuf/Struct.pbobjc.h
index 3e2d55fd..3fc80caa 100644
--- a/objectivec/google/protobuf/Struct.pbobjc.h
+++ b/objectivec/google/protobuf/Struct.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -32,35 +35,43 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Enum GPBNullValue
-/// `NullValue` is a singleton enumeration to represent the null value for the
-/// `Value` type union.
-///
-/// The JSON representation for `NullValue` is JSON `null`.
+/**
+ * `NullValue` is a singleton enumeration to represent the null value for the
+ * `Value` type union.
+ *
+ * The JSON representation for `NullValue` is JSON `null`.
+ **/
typedef GPB_ENUM(GPBNullValue) {
- /// Value used if any message's field encounters a value that is not defined
- /// by this enum. The message will also have C functions to get/set the rawValue
- /// of the field.
+ /**
+ * Value used if any message's field encounters a value that is not defined
+ * by this enum. The message will also have C functions to get/set the rawValue
+ * of the field.
+ **/
GPBNullValue_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /// Null value.
+ /** Null value. */
GPBNullValue_NullValue = 0,
};
GPBEnumDescriptor *GPBNullValue_EnumDescriptor(void);
-/// Checks to see if the given value is defined by the enum or was not known at
-/// the time this source was generated.
+/**
+ * Checks to see if the given value is defined by the enum or was not known at
+ * the time this source was generated.
+ **/
BOOL GPBNullValue_IsValidValue(int32_t value);
#pragma mark - GPBStructRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBStructRoot : GPBRootObject
@end
@@ -70,19 +81,21 @@ typedef GPB_ENUM(GPBStruct_FieldNumber) {
GPBStruct_FieldNumber_Fields = 1,
};
-/// `Struct` represents a structured data value, consisting of fields
-/// which map to dynamically typed values. In some languages, `Struct`
-/// might be supported by a native representation. For example, in
-/// scripting languages like JS a struct is represented as an
-/// object. The details of that representation are described together
-/// with the proto support for the language.
-///
-/// The JSON representation for `Struct` is JSON object.
+/**
+ * `Struct` represents a structured data value, consisting of fields
+ * which map to dynamically typed values. In some languages, `Struct`
+ * might be supported by a native representation. For example, in
+ * scripting languages like JS a struct is represented as an
+ * object. The details of that representation are described together
+ * with the proto support for the language.
+ *
+ * The JSON representation for `Struct` is JSON object.
+ **/
@interface GPBStruct : GPBMessage
-/// Unordered map of dynamically typed values.
+/** Unordered map of dynamically typed values. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableDictionary<NSString*, GPBValue*> *fields;
-/// The number of items in @c fields without causing the array to be created.
+/** The number of items in @c fields without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger fields_Count;
@end
@@ -108,46 +121,54 @@ typedef GPB_ENUM(GPBValue_Kind_OneOfCase) {
GPBValue_Kind_OneOfCase_ListValue = 6,
};
-/// `Value` represents a dynamically typed value which can be either
-/// null, a number, a string, a boolean, a recursive struct value, or a
-/// list of values. A producer of value is expected to set one of that
-/// variants, absence of any variant indicates an error.
-///
-/// The JSON representation for `Value` is JSON value.
+/**
+ * `Value` represents a dynamically typed value which can be either
+ * null, a number, a string, a boolean, a recursive struct value, or a
+ * list of values. A producer of value is expected to set one of that
+ * variants, absence of any variant indicates an error.
+ *
+ * The JSON representation for `Value` is JSON value.
+ **/
@interface GPBValue : GPBMessage
-/// The kind of value.
+/** The kind of value. */
@property(nonatomic, readonly) GPBValue_Kind_OneOfCase kindOneOfCase;
-/// Represents a null value.
+/** Represents a null value. */
@property(nonatomic, readwrite) GPBNullValue nullValue;
-/// Represents a double value.
+/** Represents a double value. */
@property(nonatomic, readwrite) double numberValue;
-/// Represents a string value.
+/** Represents a string value. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *stringValue;
-/// Represents a boolean value.
+/** Represents a boolean value. */
@property(nonatomic, readwrite) BOOL boolValue;
-/// Represents a structured value.
+/** Represents a structured value. */
@property(nonatomic, readwrite, strong, null_resettable) GPBStruct *structValue;
-/// Represents a repeated `Value`.
+/** Represents a repeated `Value`. */
@property(nonatomic, readwrite, strong, null_resettable) GPBListValue *listValue;
@end
-/// Fetches the raw value of a @c GPBValue's @c nullValue property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBValue's @c nullValue property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBValue_NullValue_RawValue(GPBValue *message);
-/// Sets the raw value of an @c GPBValue's @c nullValue property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBValue's @c nullValue property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBValue_NullValue_RawValue(GPBValue *message, int32_t value);
-/// Clears whatever value was set for the oneof 'kind'.
+/**
+ * Clears whatever value was set for the oneof 'kind'.
+ **/
void GPBValue_ClearKindOneOfCase(GPBValue *message);
#pragma mark - GPBListValue
@@ -156,14 +177,16 @@ typedef GPB_ENUM(GPBListValue_FieldNumber) {
GPBListValue_FieldNumber_ValuesArray = 1,
};
-/// `ListValue` is a wrapper around a repeated field of values.
-///
-/// The JSON representation for `ListValue` is JSON array.
+/**
+ * `ListValue` is a wrapper around a repeated field of values.
+ *
+ * The JSON representation for `ListValue` is JSON array.
+ **/
@interface GPBListValue : GPBMessage
-/// Repeated field of dynamically typed values.
+/** Repeated field of dynamically typed values. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBValue*> *valuesArray;
-/// The number of items in @c valuesArray without causing the array to be created.
+/** The number of items in @c valuesArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger valuesArray_Count;
@end
diff --git a/objectivec/google/protobuf/Struct.pbobjc.m b/objectivec/google/protobuf/Struct.pbobjc.m
index 8ea1f124..f36ec582 100644
--- a/objectivec/google/protobuf/Struct.pbobjc.m
+++ b/objectivec/google/protobuf/Struct.pbobjc.m
@@ -28,6 +28,9 @@
@implementation GPBStructRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBStructRoot_FileDescriptor
@@ -37,8 +40,9 @@ static GPBFileDescriptor *GPBStructRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -110,7 +114,7 @@ typedef struct GPBStruct__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBStruct__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -152,7 +156,7 @@ typedef struct GPBValue__storage_ {
.number = GPBValue_FieldNumber_NullValue,
.hasIndex = -1,
.offset = (uint32_t)offsetof(GPBValue__storage_, nullValue),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
{
@@ -208,7 +212,7 @@ typedef struct GPBValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
static const char *oneofs[] = {
"kind",
};
@@ -274,7 +278,7 @@ typedef struct GPBListValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBListValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.h b/objectivec/google/protobuf/Timestamp.pbobjc.h
index d15de7c7..9c83d094 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.h
+++ b/objectivec/google/protobuf/Timestamp.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,14 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBTimestampRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBTimestampRoot : GPBRootObject
@end
@@ -46,70 +51,74 @@ typedef GPB_ENUM(GPBTimestamp_FieldNumber) {
GPBTimestamp_FieldNumber_Nanos = 2,
};
-/// A Timestamp represents a point in time independent of any time zone
-/// or calendar, represented as seconds and fractions of seconds at
-/// nanosecond resolution in UTC Epoch time. It is encoded using the
-/// Proleptic Gregorian Calendar which extends the Gregorian calendar
-/// backwards to year one. It is encoded assuming all minutes are 60
-/// seconds long, i.e. leap seconds are "smeared" so that no leap second
-/// table is needed for interpretation. Range is from
-/// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
-/// By restricting to that range, we ensure that we can convert to
-/// and from RFC 3339 date strings.
-/// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
-///
-/// Example 1: Compute Timestamp from POSIX `time()`.
-///
-/// Timestamp timestamp;
-/// timestamp.set_seconds(time(NULL));
-/// timestamp.set_nanos(0);
-///
-/// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
-///
-/// struct timeval tv;
-/// gettimeofday(&tv, NULL);
-///
-/// Timestamp timestamp;
-/// timestamp.set_seconds(tv.tv_sec);
-/// timestamp.set_nanos(tv.tv_usec * 1000);
-///
-/// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
-///
-/// FILETIME ft;
-/// GetSystemTimeAsFileTime(&ft);
-/// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
-///
-/// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
-/// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
-/// Timestamp timestamp;
-/// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
-/// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
-///
-/// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
-///
-/// long millis = System.currentTimeMillis();
-///
-/// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
-/// .setNanos((int) ((millis % 1000) * 1000000)).build();
-///
-///
-/// Example 5: Compute Timestamp from current time in Python.
-///
-/// now = time.time()
-/// seconds = int(now)
-/// nanos = int((now - seconds) * 10**9)
-/// timestamp = Timestamp(seconds=seconds, nanos=nanos)
+/**
+ * A Timestamp represents a point in time independent of any time zone
+ * or calendar, represented as seconds and fractions of seconds at
+ * nanosecond resolution in UTC Epoch time. It is encoded using the
+ * Proleptic Gregorian Calendar which extends the Gregorian calendar
+ * backwards to year one. It is encoded assuming all minutes are 60
+ * seconds long, i.e. leap seconds are "smeared" so that no leap second
+ * table is needed for interpretation. Range is from
+ * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+ * By restricting to that range, we ensure that we can convert to
+ * and from RFC 3339 date strings.
+ * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+ *
+ * Example 1: Compute Timestamp from POSIX `time()`.
+ *
+ * Timestamp timestamp;
+ * timestamp.set_seconds(time(NULL));
+ * timestamp.set_nanos(0);
+ *
+ * Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+ *
+ * struct timeval tv;
+ * gettimeofday(&tv, NULL);
+ *
+ * Timestamp timestamp;
+ * timestamp.set_seconds(tv.tv_sec);
+ * timestamp.set_nanos(tv.tv_usec * 1000);
+ *
+ * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+ *
+ * FILETIME ft;
+ * GetSystemTimeAsFileTime(&ft);
+ * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+ *
+ * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+ * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+ * Timestamp timestamp;
+ * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+ * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+ *
+ * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+ *
+ * long millis = System.currentTimeMillis();
+ *
+ * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+ * .setNanos((int) ((millis % 1000) * 1000000)).build();
+ *
+ *
+ * Example 5: Compute Timestamp from current time in Python.
+ *
+ * timestamp = Timestamp()
+ * timestamp.GetCurrentTime()
+ **/
@interface GPBTimestamp : GPBMessage
-/// Represents seconds of UTC time since Unix epoch
-/// 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
-/// 9999-12-31T23:59:59Z inclusive.
+/**
+ * Represents seconds of UTC time since Unix epoch
+ * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ * 9999-12-31T23:59:59Z inclusive.
+ **/
@property(nonatomic, readwrite) int64_t seconds;
-/// Non-negative fractions of a second at nanosecond resolution. Negative
-/// second values with fractions must still have non-negative nanos values
-/// that count forward in time. Must be from 0 to 999,999,999
-/// inclusive.
+/**
+ * Non-negative fractions of a second at nanosecond resolution. Negative
+ * second values with fractions must still have non-negative nanos values
+ * that count forward in time. Must be from 0 to 999,999,999
+ * inclusive.
+ **/
@property(nonatomic, readwrite) int32_t nanos;
@end
diff --git a/objectivec/google/protobuf/Timestamp.pbobjc.m b/objectivec/google/protobuf/Timestamp.pbobjc.m
index 06e3ef94..4ab159fb 100644
--- a/objectivec/google/protobuf/Timestamp.pbobjc.m
+++ b/objectivec/google/protobuf/Timestamp.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBTimestampRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBTimestampRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBTimestampRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -88,7 +92,7 @@ typedef struct GPBTimestamp__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBTimestamp__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/Type.pbobjc.h b/objectivec/google/protobuf/Type.pbobjc.h
index 93ee3cec..06e75480 100644
--- a/objectivec/google/protobuf/Type.pbobjc.h
+++ b/objectivec/google/protobuf/Type.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -34,134 +37,148 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - Enum GPBSyntax
-/// The syntax in which a protocol buffer element is defined.
+/** The syntax in which a protocol buffer element is defined. */
typedef GPB_ENUM(GPBSyntax) {
- /// Value used if any message's field encounters a value that is not defined
- /// by this enum. The message will also have C functions to get/set the rawValue
- /// of the field.
+ /**
+ * Value used if any message's field encounters a value that is not defined
+ * by this enum. The message will also have C functions to get/set the rawValue
+ * of the field.
+ **/
GPBSyntax_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /// Syntax `proto2`.
+ /** Syntax `proto2`. */
GPBSyntax_SyntaxProto2 = 0,
- /// Syntax `proto3`.
+ /** Syntax `proto3`. */
GPBSyntax_SyntaxProto3 = 1,
};
GPBEnumDescriptor *GPBSyntax_EnumDescriptor(void);
-/// Checks to see if the given value is defined by the enum or was not known at
-/// the time this source was generated.
+/**
+ * Checks to see if the given value is defined by the enum or was not known at
+ * the time this source was generated.
+ **/
BOOL GPBSyntax_IsValidValue(int32_t value);
#pragma mark - Enum GPBField_Kind
-/// Basic field types.
+/** Basic field types. */
typedef GPB_ENUM(GPBField_Kind) {
- /// Value used if any message's field encounters a value that is not defined
- /// by this enum. The message will also have C functions to get/set the rawValue
- /// of the field.
+ /**
+ * Value used if any message's field encounters a value that is not defined
+ * by this enum. The message will also have C functions to get/set the rawValue
+ * of the field.
+ **/
GPBField_Kind_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /// Field type unknown.
+ /** Field type unknown. */
GPBField_Kind_TypeUnknown = 0,
- /// Field type double.
+ /** Field type double. */
GPBField_Kind_TypeDouble = 1,
- /// Field type float.
+ /** Field type float. */
GPBField_Kind_TypeFloat = 2,
- /// Field type int64.
+ /** Field type int64. */
GPBField_Kind_TypeInt64 = 3,
- /// Field type uint64.
+ /** Field type uint64. */
GPBField_Kind_TypeUint64 = 4,
- /// Field type int32.
+ /** Field type int32. */
GPBField_Kind_TypeInt32 = 5,
- /// Field type fixed64.
+ /** Field type fixed64. */
GPBField_Kind_TypeFixed64 = 6,
- /// Field type fixed32.
+ /** Field type fixed32. */
GPBField_Kind_TypeFixed32 = 7,
- /// Field type bool.
+ /** Field type bool. */
GPBField_Kind_TypeBool = 8,
- /// Field type string.
+ /** Field type string. */
GPBField_Kind_TypeString = 9,
- /// Field type group. Proto2 syntax only, and deprecated.
+ /** Field type group. Proto2 syntax only, and deprecated. */
GPBField_Kind_TypeGroup = 10,
- /// Field type message.
+ /** Field type message. */
GPBField_Kind_TypeMessage = 11,
- /// Field type bytes.
+ /** Field type bytes. */
GPBField_Kind_TypeBytes = 12,
- /// Field type uint32.
+ /** Field type uint32. */
GPBField_Kind_TypeUint32 = 13,
- /// Field type enum.
+ /** Field type enum. */
GPBField_Kind_TypeEnum = 14,
- /// Field type sfixed32.
+ /** Field type sfixed32. */
GPBField_Kind_TypeSfixed32 = 15,
- /// Field type sfixed64.
+ /** Field type sfixed64. */
GPBField_Kind_TypeSfixed64 = 16,
- /// Field type sint32.
+ /** Field type sint32. */
GPBField_Kind_TypeSint32 = 17,
- /// Field type sint64.
+ /** Field type sint64. */
GPBField_Kind_TypeSint64 = 18,
};
GPBEnumDescriptor *GPBField_Kind_EnumDescriptor(void);
-/// Checks to see if the given value is defined by the enum or was not known at
-/// the time this source was generated.
+/**
+ * Checks to see if the given value is defined by the enum or was not known at
+ * the time this source was generated.
+ **/
BOOL GPBField_Kind_IsValidValue(int32_t value);
#pragma mark - Enum GPBField_Cardinality
-/// Whether a field is optional, required, or repeated.
+/** Whether a field is optional, required, or repeated. */
typedef GPB_ENUM(GPBField_Cardinality) {
- /// Value used if any message's field encounters a value that is not defined
- /// by this enum. The message will also have C functions to get/set the rawValue
- /// of the field.
+ /**
+ * Value used if any message's field encounters a value that is not defined
+ * by this enum. The message will also have C functions to get/set the rawValue
+ * of the field.
+ **/
GPBField_Cardinality_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
- /// For fields with unknown cardinality.
+ /** For fields with unknown cardinality. */
GPBField_Cardinality_CardinalityUnknown = 0,
- /// For optional fields.
+ /** For optional fields. */
GPBField_Cardinality_CardinalityOptional = 1,
- /// For required fields. Proto2 syntax only.
+ /** For required fields. Proto2 syntax only. */
GPBField_Cardinality_CardinalityRequired = 2,
- /// For repeated fields.
+ /** For repeated fields. */
GPBField_Cardinality_CardinalityRepeated = 3,
};
GPBEnumDescriptor *GPBField_Cardinality_EnumDescriptor(void);
-/// Checks to see if the given value is defined by the enum or was not known at
-/// the time this source was generated.
+/**
+ * Checks to see if the given value is defined by the enum or was not known at
+ * the time this source was generated.
+ **/
BOOL GPBField_Cardinality_IsValidValue(int32_t value);
#pragma mark - GPBTypeRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBTypeRoot : GPBRootObject
@end
@@ -176,43 +193,49 @@ typedef GPB_ENUM(GPBType_FieldNumber) {
GPBType_FieldNumber_Syntax = 6,
};
-/// A protocol buffer message type.
+/**
+ * A protocol buffer message type.
+ **/
@interface GPBType : GPBMessage
-/// The fully qualified message name.
+/** The fully qualified message name. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// The list of fields.
+/** The list of fields. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBField*> *fieldsArray;
-/// The number of items in @c fieldsArray without causing the array to be created.
+/** The number of items in @c fieldsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger fieldsArray_Count;
-/// The list of types appearing in `oneof` definitions in this type.
+/** The list of types appearing in `oneof` definitions in this type. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<NSString*> *oneofsArray;
-/// The number of items in @c oneofsArray without causing the array to be created.
+/** The number of items in @c oneofsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger oneofsArray_Count;
-/// The protocol buffer options.
+/** The protocol buffer options. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/// The number of items in @c optionsArray without causing the array to be created.
+/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-/// The source context.
+/** The source context. */
@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
-/// Test to see if @c sourceContext has been set.
+/** Test to see if @c sourceContext has been set. */
@property(nonatomic, readwrite) BOOL hasSourceContext;
-/// The source syntax.
+/** The source syntax. */
@property(nonatomic, readwrite) GPBSyntax syntax;
@end
-/// Fetches the raw value of a @c GPBType's @c syntax property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBType's @c syntax property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBType_Syntax_RawValue(GPBType *message);
-/// Sets the raw value of an @c GPBType's @c syntax property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBType's @c syntax property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBType_Syntax_RawValue(GPBType *message, int32_t value);
#pragma mark - GPBField
@@ -230,59 +253,73 @@ typedef GPB_ENUM(GPBField_FieldNumber) {
GPBField_FieldNumber_DefaultValue = 11,
};
-/// A single field of a message type.
+/**
+ * A single field of a message type.
+ **/
@interface GPBField : GPBMessage
-/// The field type.
+/** The field type. */
@property(nonatomic, readwrite) GPBField_Kind kind;
-/// The field cardinality.
+/** The field cardinality. */
@property(nonatomic, readwrite) GPBField_Cardinality cardinality;
-/// The field number.
+/** The field number. */
@property(nonatomic, readwrite) int32_t number;
-/// The field name.
+/** The field name. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// The field type URL, without the scheme, for message or enumeration
-/// types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
+/**
+ * The field type URL, without the scheme, for message or enumeration
+ * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`.
+ **/
@property(nonatomic, readwrite, copy, null_resettable) NSString *typeURL;
-/// The index of the field type in `Type.oneofs`, for message or enumeration
-/// types. The first type has index 1; zero means the type is not in the list.
+/**
+ * The index of the field type in `Type.oneofs`, for message or enumeration
+ * types. The first type has index 1; zero means the type is not in the list.
+ **/
@property(nonatomic, readwrite) int32_t oneofIndex;
-/// Whether to use alternative packed wire representation.
+/** Whether to use alternative packed wire representation. */
@property(nonatomic, readwrite) BOOL packed;
-/// The protocol buffer options.
+/** The protocol buffer options. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/// The number of items in @c optionsArray without causing the array to be created.
+/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-/// The field JSON name.
+/** The field JSON name. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *jsonName;
-/// The string value of the default value of this field. Proto2 syntax only.
+/** The string value of the default value of this field. Proto2 syntax only. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *defaultValue;
@end
-/// Fetches the raw value of a @c GPBField's @c kind property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBField's @c kind property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBField_Kind_RawValue(GPBField *message);
-/// Sets the raw value of an @c GPBField's @c kind property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBField's @c kind property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBField_Kind_RawValue(GPBField *message, int32_t value);
-/// Fetches the raw value of a @c GPBField's @c cardinality property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBField's @c cardinality property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBField_Cardinality_RawValue(GPBField *message);
-/// Sets the raw value of an @c GPBField's @c cardinality property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBField's @c cardinality property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBField_Cardinality_RawValue(GPBField *message, int32_t value);
#pragma mark - GPBEnum
@@ -295,38 +332,44 @@ typedef GPB_ENUM(GPBEnum_FieldNumber) {
GPBEnum_FieldNumber_Syntax = 5,
};
-/// Enum type definition.
+/**
+ * Enum type definition.
+ **/
@interface GPBEnum : GPBMessage
-/// Enum type name.
+/** Enum type name. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// Enum value definitions.
+/** Enum value definitions. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBEnumValue*> *enumvalueArray;
-/// The number of items in @c enumvalueArray without causing the array to be created.
+/** The number of items in @c enumvalueArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger enumvalueArray_Count;
-/// Protocol buffer options.
+/** Protocol buffer options. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/// The number of items in @c optionsArray without causing the array to be created.
+/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
-/// The source context.
+/** The source context. */
@property(nonatomic, readwrite, strong, null_resettable) GPBSourceContext *sourceContext;
-/// Test to see if @c sourceContext has been set.
+/** Test to see if @c sourceContext has been set. */
@property(nonatomic, readwrite) BOOL hasSourceContext;
-/// The source syntax.
+/** The source syntax. */
@property(nonatomic, readwrite) GPBSyntax syntax;
@end
-/// Fetches the raw value of a @c GPBEnum's @c syntax property, even
-/// if the value was not defined by the enum at the time the code was generated.
+/**
+ * Fetches the raw value of a @c GPBEnum's @c syntax property, even
+ * if the value was not defined by the enum at the time the code was generated.
+ **/
int32_t GPBEnum_Syntax_RawValue(GPBEnum *message);
-/// Sets the raw value of an @c GPBEnum's @c syntax property, allowing
-/// it to be set to a value that was not defined by the enum at the time the code
-/// was generated.
+/**
+ * Sets the raw value of an @c GPBEnum's @c syntax property, allowing
+ * it to be set to a value that was not defined by the enum at the time the code
+ * was generated.
+ **/
void SetGPBEnum_Syntax_RawValue(GPBEnum *message, int32_t value);
#pragma mark - GPBEnumValue
@@ -337,18 +380,20 @@ typedef GPB_ENUM(GPBEnumValue_FieldNumber) {
GPBEnumValue_FieldNumber_OptionsArray = 3,
};
-/// Enum value definition.
+/**
+ * Enum value definition.
+ **/
@interface GPBEnumValue : GPBMessage
-/// Enum value name.
+/** Enum value name. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// Enum value number.
+/** Enum value number. */
@property(nonatomic, readwrite) int32_t number;
-/// Protocol buffer options.
+/** Protocol buffer options. */
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray<GPBOption*> *optionsArray;
-/// The number of items in @c optionsArray without causing the array to be created.
+/** The number of items in @c optionsArray without causing the array to be created. */
@property(nonatomic, readonly) NSUInteger optionsArray_Count;
@end
@@ -360,16 +405,18 @@ typedef GPB_ENUM(GPBOption_FieldNumber) {
GPBOption_FieldNumber_Value = 2,
};
-/// A protocol buffer option, which can be attached to a message, field,
-/// enumeration, etc.
+/**
+ * A protocol buffer option, which can be attached to a message, field,
+ * enumeration, etc.
+ **/
@interface GPBOption : GPBMessage
-/// The option's name. For example, `"java_package"`.
+/** The option's name. For example, `"java_package"`. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *name;
-/// The option's value. For example, `"com.google.protobuf"`.
+/** The option's value. For example, `"com.google.protobuf"`. */
@property(nonatomic, readwrite, strong, null_resettable) GPBAny *value;
-/// Test to see if @c value has been set.
+/** Test to see if @c value has been set. */
@property(nonatomic, readwrite) BOOL hasValue;
@end
diff --git a/objectivec/google/protobuf/Type.pbobjc.m b/objectivec/google/protobuf/Type.pbobjc.m
index 6c7b4efd..7a949388 100644
--- a/objectivec/google/protobuf/Type.pbobjc.m
+++ b/objectivec/google/protobuf/Type.pbobjc.m
@@ -31,18 +31,8 @@
@implementation GPBTypeRoot
-+ (GPBExtensionRegistry*)extensionRegistry {
- // This is called by +initialize so there is no need to worry
- // about thread safety and initialization of registry.
- static GPBExtensionRegistry* registry = nil;
- if (!registry) {
- GPBDebugCheckRuntimeVersion();
- registry = [[GPBExtensionRegistry alloc] init];
- [registry addExtensions:[GPBAnyRoot extensionRegistry]];
- [registry addExtensions:[GPBSourceContextRoot extensionRegistry]];
- }
- return registry;
-}
+// No extensions in the file and none of the imports (direct or indirect)
+// defined extensions, so no need to generate +extensionRegistry.
@end
@@ -53,8 +43,9 @@ static GPBFileDescriptor *GPBTypeRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -172,7 +163,7 @@ typedef struct GPBType__storage_ {
.number = GPBType_FieldNumber_Syntax,
.hasIndex = 2,
.offset = (uint32_t)offsetof(GPBType__storage_, syntax),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
};
@@ -183,7 +174,7 @@ typedef struct GPBType__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBType__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -244,7 +235,7 @@ typedef struct GPBField__storage_ {
.number = GPBField_FieldNumber_Kind,
.hasIndex = 0,
.offset = (uint32_t)offsetof(GPBField__storage_, kind),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
{
@@ -253,7 +244,7 @@ typedef struct GPBField__storage_ {
.number = GPBField_FieldNumber_Cardinality,
.hasIndex = 1,
.offset = (uint32_t)offsetof(GPBField__storage_, cardinality),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
{
@@ -280,7 +271,7 @@ typedef struct GPBField__storage_ {
.number = GPBField_FieldNumber_TypeURL,
.hasIndex = 4,
.offset = (uint32_t)offsetof(GPBField__storage_, typeURL),
- .flags = GPBFieldOptional | GPBFieldTextFormatNameCustom,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldTextFormatNameCustom),
.dataType = GPBDataTypeString,
},
{
@@ -336,7 +327,7 @@ typedef struct GPBField__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBField__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS
static const char *extraTextFormatInfo =
"\001\006\004\241!!\000";
@@ -553,7 +544,7 @@ typedef struct GPBEnum__storage_ {
.number = GPBEnum_FieldNumber_Syntax,
.hasIndex = 2,
.offset = (uint32_t)offsetof(GPBEnum__storage_, syntax),
- .flags = GPBFieldOptional | GPBFieldHasEnumDescriptor,
+ .flags = (GPBFieldFlags)(GPBFieldOptional | GPBFieldHasEnumDescriptor),
.dataType = GPBDataTypeEnum,
},
};
@@ -564,7 +555,7 @@ typedef struct GPBEnum__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBEnum__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -641,7 +632,7 @@ typedef struct GPBEnumValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBEnumValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -695,7 +686,7 @@ typedef struct GPBOption__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBOption__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/objectivec/google/protobuf/Wrappers.pbobjc.h b/objectivec/google/protobuf/Wrappers.pbobjc.h
index 5593d348..3cb9fe77 100644
--- a/objectivec/google/protobuf/Wrappers.pbobjc.h
+++ b/objectivec/google/protobuf/Wrappers.pbobjc.h
@@ -13,8 +13,11 @@
#import "GPBProtocolBuffers.h"
#endif
-#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
-#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
+#if GOOGLE_PROTOBUF_OBJC_VERSION < 30002
+#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.
+#endif
+#if 30002 < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION
+#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.
#endif
// @@protoc_insertion_point(imports)
@@ -28,14 +31,16 @@ NS_ASSUME_NONNULL_BEGIN
#pragma mark - GPBWrappersRoot
-/// Exposes the extension registry for this file.
-///
-/// The base class provides:
-/// @code
-/// + (GPBExtensionRegistry *)extensionRegistry;
-/// @endcode
-/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
-/// this file and all files that it depends on.
+/**
+ * Exposes the extension registry for this file.
+ *
+ * The base class provides:
+ * @code
+ * + (GPBExtensionRegistry *)extensionRegistry;
+ * @endcode
+ * which is a @c GPBExtensionRegistry that includes all the extensions defined by
+ * this file and all files that it depends on.
+ **/
@interface GPBWrappersRoot : GPBRootObject
@end
@@ -45,12 +50,14 @@ typedef GPB_ENUM(GPBDoubleValue_FieldNumber) {
GPBDoubleValue_FieldNumber_Value = 1,
};
-/// Wrapper message for `double`.
-///
-/// The JSON representation for `DoubleValue` is JSON number.
+/**
+ * Wrapper message for `double`.
+ *
+ * The JSON representation for `DoubleValue` is JSON number.
+ **/
@interface GPBDoubleValue : GPBMessage
-/// The double value.
+/** The double value. */
@property(nonatomic, readwrite) double value;
@end
@@ -61,12 +68,14 @@ typedef GPB_ENUM(GPBFloatValue_FieldNumber) {
GPBFloatValue_FieldNumber_Value = 1,
};
-/// Wrapper message for `float`.
-///
-/// The JSON representation for `FloatValue` is JSON number.
+/**
+ * Wrapper message for `float`.
+ *
+ * The JSON representation for `FloatValue` is JSON number.
+ **/
@interface GPBFloatValue : GPBMessage
-/// The float value.
+/** The float value. */
@property(nonatomic, readwrite) float value;
@end
@@ -77,12 +86,14 @@ typedef GPB_ENUM(GPBInt64Value_FieldNumber) {
GPBInt64Value_FieldNumber_Value = 1,
};
-/// Wrapper message for `int64`.
-///
-/// The JSON representation for `Int64Value` is JSON string.
+/**
+ * Wrapper message for `int64`.
+ *
+ * The JSON representation for `Int64Value` is JSON string.
+ **/
@interface GPBInt64Value : GPBMessage
-/// The int64 value.
+/** The int64 value. */
@property(nonatomic, readwrite) int64_t value;
@end
@@ -93,12 +104,14 @@ typedef GPB_ENUM(GPBUInt64Value_FieldNumber) {
GPBUInt64Value_FieldNumber_Value = 1,
};
-/// Wrapper message for `uint64`.
-///
-/// The JSON representation for `UInt64Value` is JSON string.
+/**
+ * Wrapper message for `uint64`.
+ *
+ * The JSON representation for `UInt64Value` is JSON string.
+ **/
@interface GPBUInt64Value : GPBMessage
-/// The uint64 value.
+/** The uint64 value. */
@property(nonatomic, readwrite) uint64_t value;
@end
@@ -109,12 +122,14 @@ typedef GPB_ENUM(GPBInt32Value_FieldNumber) {
GPBInt32Value_FieldNumber_Value = 1,
};
-/// Wrapper message for `int32`.
-///
-/// The JSON representation for `Int32Value` is JSON number.
+/**
+ * Wrapper message for `int32`.
+ *
+ * The JSON representation for `Int32Value` is JSON number.
+ **/
@interface GPBInt32Value : GPBMessage
-/// The int32 value.
+/** The int32 value. */
@property(nonatomic, readwrite) int32_t value;
@end
@@ -125,12 +140,14 @@ typedef GPB_ENUM(GPBUInt32Value_FieldNumber) {
GPBUInt32Value_FieldNumber_Value = 1,
};
-/// Wrapper message for `uint32`.
-///
-/// The JSON representation for `UInt32Value` is JSON number.
+/**
+ * Wrapper message for `uint32`.
+ *
+ * The JSON representation for `UInt32Value` is JSON number.
+ **/
@interface GPBUInt32Value : GPBMessage
-/// The uint32 value.
+/** The uint32 value. */
@property(nonatomic, readwrite) uint32_t value;
@end
@@ -141,12 +158,14 @@ typedef GPB_ENUM(GPBBoolValue_FieldNumber) {
GPBBoolValue_FieldNumber_Value = 1,
};
-/// Wrapper message for `bool`.
-///
-/// The JSON representation for `BoolValue` is JSON `true` and `false`.
+/**
+ * Wrapper message for `bool`.
+ *
+ * The JSON representation for `BoolValue` is JSON `true` and `false`.
+ **/
@interface GPBBoolValue : GPBMessage
-/// The bool value.
+/** The bool value. */
@property(nonatomic, readwrite) BOOL value;
@end
@@ -157,12 +176,14 @@ typedef GPB_ENUM(GPBStringValue_FieldNumber) {
GPBStringValue_FieldNumber_Value = 1,
};
-/// Wrapper message for `string`.
-///
-/// The JSON representation for `StringValue` is JSON string.
+/**
+ * Wrapper message for `string`.
+ *
+ * The JSON representation for `StringValue` is JSON string.
+ **/
@interface GPBStringValue : GPBMessage
-/// The string value.
+/** The string value. */
@property(nonatomic, readwrite, copy, null_resettable) NSString *value;
@end
@@ -173,12 +194,14 @@ typedef GPB_ENUM(GPBBytesValue_FieldNumber) {
GPBBytesValue_FieldNumber_Value = 1,
};
-/// Wrapper message for `bytes`.
-///
-/// The JSON representation for `BytesValue` is JSON string.
+/**
+ * Wrapper message for `bytes`.
+ *
+ * The JSON representation for `BytesValue` is JSON string.
+ **/
@interface GPBBytesValue : GPBMessage
-/// The bytes value.
+/** The bytes value. */
@property(nonatomic, readwrite, copy, null_resettable) NSData *value;
@end
diff --git a/objectivec/google/protobuf/Wrappers.pbobjc.m b/objectivec/google/protobuf/Wrappers.pbobjc.m
index b5405a7d..5479eb12 100644
--- a/objectivec/google/protobuf/Wrappers.pbobjc.m
+++ b/objectivec/google/protobuf/Wrappers.pbobjc.m
@@ -27,6 +27,9 @@
@implementation GPBWrappersRoot
+// No extensions in the file and no imports, so no need to generate
+// +extensionRegistry.
+
@end
#pragma mark - GPBWrappersRoot_FileDescriptor
@@ -36,8 +39,9 @@ static GPBFileDescriptor *GPBWrappersRoot_FileDescriptor(void) {
// about thread safety of the singleton.
static GPBFileDescriptor *descriptor = NULL;
if (!descriptor) {
- GPBDebugCheckRuntimeVersion();
+ GPB_DEBUG_CHECK_RUNTIME_VERSIONS();
descriptor = [[GPBFileDescriptor alloc] initWithPackage:@"google.protobuf"
+ objcPrefix:@"GPB"
syntax:GPBFileSyntaxProto3];
}
return descriptor;
@@ -77,7 +81,7 @@ typedef struct GPBDoubleValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBDoubleValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -120,7 +124,7 @@ typedef struct GPBFloatValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBFloatValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -163,7 +167,7 @@ typedef struct GPBInt64Value__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBInt64Value__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -206,7 +210,7 @@ typedef struct GPBUInt64Value__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBUInt64Value__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -249,7 +253,7 @@ typedef struct GPBInt32Value__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBInt32Value__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -292,7 +296,7 @@ typedef struct GPBUInt32Value__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBUInt32Value__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -334,7 +338,7 @@ typedef struct GPBBoolValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBBoolValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -377,7 +381,7 @@ typedef struct GPBStringValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBStringValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
@@ -420,7 +424,7 @@ typedef struct GPBBytesValue__storage_ {
fields:fields
fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription))
storageSize:sizeof(GPBBytesValue__storage_)
- flags:0];
+ flags:GPBDescriptorInitializationFlag_None];
NSAssert(descriptor == nil, @"Startup recursed!");
descriptor = localDescriptor;
}
diff --git a/php/README.md b/php/README.md
new file mode 100644
index 00000000..ec92d329
--- /dev/null
+++ b/php/README.md
@@ -0,0 +1,99 @@
+This directory contains the Protocol Buffers runtime implementation via both a
+pure PHP package and a native c extension. The pure PHP package is intended to
+provide usability to wider range of PHP platforms, while the c extension is
+intended to provide higher performance. Both implementations provide the same
+runtime APIs and share the same generated code. Users don’t need to re-generate
+code for the same proto definition when they want to switch the implementation
+later.
+
+Both implementations make use of generated PHP code that defines message and
+enum types in PHP. We strongly recommend using protoc's PHP generation support
+with .proto files. The build process in this directory only installs the
+extension/package; you need to install protoc as well to have PHP code
+generation functionality.
+
+## Requirements
+
+To use PHP runtime library requires:
+
+- C extension: PHP 5.5.x or 5.6.x.
+- PHP package: PHP 5.5, 5.6 or 7.
+
+## Installation
+
+### C Extension
+
+#### Prerequirements
+
+To install the c extension, the following tools are needed:
+* autoconf
+* automake
+* libtool
+* make
+* gcc
+* pear
+* pecl
+
+On Ubuntu, you can install them with:
+```
+sudo apt-get install php-pear php5-dev autoconf automake libtool make gcc
+```
+On other platforms, please use the corresponding package managing tool to
+install them before proceeding.
+
+#### Installation from Source (Building extension)
+
+To build the c extension, run the following command:
+```
+cd ext/google/protobuf
+pear package
+sudo pecl install protobuf-{VERSION}.tgz
+```
+
+#### Installation from PECL
+
+When we release a version of Protocol Buffers, we will upload the extension to
+[PECL](https://pecl.php.net/). To use this pre-packaged extension, simply
+install it as you would any other extension:
+
+```
+sudo pecl install protobuf-{VERSION}
+```
+
+### PHP Package
+
+#### Installation from composer
+
+Simply add "google/protobuf" to the 'require' section of composer.json in your
+project.
+
+### Protoc
+
+Once the extension or package is installed, if you wish to generate PHP code
+from a `.proto` file, you will also want to install the Protocol Buffers
+compiler (protoc), as described in this repository's main `README` file. The
+version of `protoc` included in the latest release supports the `--php_out`
+option to generate PHP code:
+```
+protoc --php_out=out_dir test.proto
+```
+
+## Usage
+
+For general guide:
+ https://developers.google.com/protocol-buffers/phptutorial/
+For generated code:
+ https://developers.google.com/protocol-buffers/docs/reference/php-generated
+
+Known Issues
+------------
+
+* Missing native support for well known types.
+* Missing support for proto2.
+* No API provided for clear/copy messages.
+* No API provided for encoding/decoding with stream.
+* Map fields may not be garbage-collected if there is cycle reference.
+* No debug information for messages in c extension.
+* HHVM not tested.
+* C extension not tested on windows, mac, php 7.0.
+* Message name cannot be Empty.
diff --git a/php/ext/google/protobuf/array.c b/php/ext/google/protobuf/array.c
new file mode 100644
index 00000000..e4a88c39
--- /dev/null
+++ b/php/ext/google/protobuf/array.c
@@ -0,0 +1,511 @@
+// 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 <ext/spl/spl_iterators.h>
+#include <Zend/zend_API.h>
+#include <Zend/zend_interfaces.h>
+
+#include "protobuf.h"
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
+ ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetSet, 0, 0, 2)
+ ZEND_ARG_INFO(0, index)
+ ZEND_ARG_INFO(0, newval)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO(arginfo_void, 0)
+ZEND_END_ARG_INFO()
+
+static zend_function_entry repeated_field_methods[] = {
+ PHP_ME(RepeatedField, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, append, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, offsetExists, arginfo_offsetGet, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, offsetGet, arginfo_offsetGet, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, offsetSet, arginfo_offsetSet, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, offsetUnset, arginfo_offsetGet, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, count, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedField, getIterator, arginfo_void, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+static zend_function_entry repeated_field_iter_methods[] = {
+ PHP_ME(RepeatedFieldIter, rewind, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedFieldIter, current, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedFieldIter, key, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedFieldIter, next, arginfo_void, ZEND_ACC_PUBLIC)
+ PHP_ME(RepeatedFieldIter, valid, arginfo_void, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+// Forward declare static functions.
+
+static zend_object_value repeated_field_create(zend_class_entry *ce TSRMLS_DC);
+static void repeated_field_free(void *object TSRMLS_DC);
+static int repeated_field_array_init(zval *array, upb_fieldtype_t type,
+ uint size ZEND_FILE_LINE_DC);
+static void repeated_field_free_element(void *object);
+static void repeated_field_write_dimension(zval *object, zval *offset,
+ zval *value TSRMLS_DC);
+static int repeated_field_has_dimension(zval *object, zval *offset TSRMLS_DC);
+static HashTable *repeated_field_get_gc(zval *object, zval ***table,
+ int *n TSRMLS_DC);
+
+static zend_object_value repeated_field_iter_create(zend_class_entry *ce TSRMLS_DC);
+static void repeated_field_iter_free(void *object TSRMLS_DC);
+
+// -----------------------------------------------------------------------------
+// RepeatedField creation/desctruction
+// -----------------------------------------------------------------------------
+
+zend_class_entry* repeated_field_type;
+zend_class_entry* repeated_field_iter_type;
+zend_object_handlers* repeated_field_handlers;
+
+void repeated_field_init(TSRMLS_D) {
+ zend_class_entry class_type;
+ const char* class_name = "Google\\Protobuf\\Internal\\RepeatedField";
+ INIT_CLASS_ENTRY_EX(class_type, class_name, strlen(class_name),
+ repeated_field_methods);
+
+ repeated_field_type = zend_register_internal_class(&class_type TSRMLS_CC);
+ repeated_field_type->create_object = repeated_field_create;
+
+ zend_class_implements(repeated_field_type TSRMLS_CC, 3, spl_ce_ArrayAccess,
+ zend_ce_aggregate, spl_ce_Countable);
+
+ repeated_field_handlers = PEMALLOC(zend_object_handlers);
+ memcpy(repeated_field_handlers, zend_get_std_object_handlers(),
+ sizeof(zend_object_handlers));
+ repeated_field_handlers->get_gc = repeated_field_get_gc;
+}
+
+static zend_object_value repeated_field_create(zend_class_entry *ce TSRMLS_DC) {
+ zend_object_value retval = {0};
+ RepeatedField *intern;
+
+ intern = emalloc(sizeof(RepeatedField));
+ memset(intern, 0, sizeof(RepeatedField));
+
+ zend_object_std_init(&intern->std, ce TSRMLS_CC);
+ object_properties_init(&intern->std, ce);
+
+ intern->array = NULL;
+ intern->type = 0;
+ intern->msg_ce = NULL;
+
+ retval.handle = zend_objects_store_put(
+ intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
+ (zend_objects_free_object_storage_t)repeated_field_free, NULL TSRMLS_CC);
+ retval.handlers = repeated_field_handlers;
+
+ return retval;
+}
+
+static void repeated_field_free(void *object TSRMLS_DC) {
+ RepeatedField *intern = object;
+ zend_object_std_dtor(&intern->std TSRMLS_CC);
+ zval_ptr_dtor(&intern->array);
+ efree(object);
+}
+
+static int repeated_field_array_init(zval *array, upb_fieldtype_t type,
+ uint size ZEND_FILE_LINE_DC) {
+ ALLOC_HASHTABLE(Z_ARRVAL_P(array));
+
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ zend_hash_init(Z_ARRVAL_P(array), size, NULL, ZVAL_PTR_DTOR, 0);
+ break;
+ default:
+ zend_hash_init(Z_ARRVAL_P(array), size, NULL, repeated_field_free_element,
+ 0);
+ }
+ Z_TYPE_P(array) = IS_ARRAY;
+ return SUCCESS;
+}
+
+static void repeated_field_free_element(void *object) {
+}
+
+// -----------------------------------------------------------------------------
+// RepeatedField Handlers
+// -----------------------------------------------------------------------------
+
+static void repeated_field_write_dimension(zval *object, zval *offset,
+ zval *value TSRMLS_DC) {
+ uint64_t index;
+
+ RepeatedField *intern = zend_object_store_get_object(object TSRMLS_CC);
+ HashTable *ht = HASH_OF(intern->array);
+ int size = native_slot_size(intern->type);
+
+ unsigned char memory[NATIVE_SLOT_MAX_SIZE];
+ memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
+
+ if (!native_slot_set(intern->type, intern->msg_ce, memory, value TSRMLS_CC)) {
+ return;
+ }
+
+ if (!offset || Z_TYPE_P(offset) == IS_NULL) {
+ index = zend_hash_num_elements(HASH_OF(intern->array));
+ } else {
+ if (protobuf_convert_to_uint64(offset, &index)) {
+ if (!zend_hash_index_exists(ht, index)) {
+ zend_error(E_USER_ERROR, "Element at %llu doesn't exist.\n", index);
+ return;
+ }
+ } else {
+ return;
+ }
+ }
+
+ zend_hash_index_update(ht, index, memory, size, NULL);
+}
+
+static HashTable *repeated_field_get_gc(zval *object, zval ***table,
+ int *n TSRMLS_DC) {
+ *table = NULL;
+ *n = 0;
+ RepeatedField *intern = zend_object_store_get_object(object TSRMLS_CC);
+ return HASH_OF(intern->array);
+}
+
+// -----------------------------------------------------------------------------
+// C RepeatedField Utilities
+// -----------------------------------------------------------------------------
+
+void *repeated_field_index_native(RepeatedField *intern, int index TSRMLS_DC) {
+ HashTable *ht = HASH_OF(intern->array);
+ void *value;
+
+ if (zend_hash_index_find(ht, index, (void **)&value) == FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %d doesn't exist.\n", index);
+ return NULL;
+ }
+
+ return value;
+}
+
+void repeated_field_push_native(RepeatedField *intern, void *value TSRMLS_DC) {
+ HashTable *ht = HASH_OF(intern->array);
+ int size = native_slot_size(intern->type);
+ zend_hash_next_index_insert(ht, (void **)value, size, NULL);
+}
+
+void repeated_field_create_with_type(zend_class_entry *ce,
+ const upb_fielddef *field,
+ zval **repeated_field TSRMLS_DC) {
+ MAKE_STD_ZVAL(*repeated_field);
+ Z_TYPE_PP(repeated_field) = IS_OBJECT;
+ Z_OBJVAL_PP(repeated_field) =
+ repeated_field_type->create_object(repeated_field_type TSRMLS_CC);
+
+ RepeatedField *intern =
+ zend_object_store_get_object(*repeated_field TSRMLS_CC);
+ intern->type = upb_fielddef_type(field);
+ if (intern->type == UPB_TYPE_MESSAGE) {
+ const upb_msgdef *msg = upb_fielddef_msgsubdef(field);
+ zval *desc_php = get_def_obj(msg);
+ Descriptor *desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ intern->msg_ce = desc->klass;
+ }
+ MAKE_STD_ZVAL(intern->array);
+ repeated_field_array_init(intern->array, intern->type, 0 ZEND_FILE_LINE_CC);
+
+ // TODO(teboring): Link class entry for message and enum
+}
+
+
+// -----------------------------------------------------------------------------
+// PHP RepeatedField Methods
+// -----------------------------------------------------------------------------
+
+/**
+ * Constructs an instance of RepeatedField.
+ * @param long Type of the stored element.
+ * @param string Message/Enum class name (message/enum fields only).
+ */
+PHP_METHOD(RepeatedField, __construct) {
+ long type;
+ zend_class_entry* klass = NULL;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|C", &type, &klass) ==
+ FAILURE) {
+ return;
+ }
+
+ RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ intern->type = to_fieldtype(type);
+ intern->msg_ce = klass;
+
+ MAKE_STD_ZVAL(intern->array);
+ repeated_field_array_init(intern->array, intern->type, 0 ZEND_FILE_LINE_CC);
+
+ if (intern->type == UPB_TYPE_MESSAGE && klass == NULL) {
+ zend_error(E_USER_ERROR, "Message type must have concrete class.");
+ return;
+ }
+
+ // TODO(teboring): Consider enum.
+}
+
+/**
+ * Append element to the end of the repeated field.
+ * @param object The element to be added.
+ */
+PHP_METHOD(RepeatedField, append) {
+ zval *value;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &value) ==
+ FAILURE) {
+ return;
+ }
+ repeated_field_write_dimension(getThis(), NULL, value TSRMLS_CC);
+}
+
+/**
+ * Check whether the element at given index exists.
+ * @param long The index to be checked.
+ * @return bool True if the element at the given index exists.
+ */
+PHP_METHOD(RepeatedField, offsetExists) {
+ long index;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ return;
+ }
+
+ RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ RETURN_BOOL(index >= 0 &&
+ index < zend_hash_num_elements(HASH_OF(intern->array)));
+}
+
+/**
+ * Return the element at the given index.
+ * This will also be called for: $ele = $arr[0]
+ * @param long The index of the element to be fetched.
+ * @return object The stored element at given index.
+ * @exception Invalid type for index.
+ * @exception Non-existing index.
+ */
+PHP_METHOD(RepeatedField, offsetGet) {
+ long index;
+ void *memory;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ return;
+ }
+
+ RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ HashTable *table = HASH_OF(intern->array);
+
+ if (zend_hash_index_find(table, index, (void **)&memory) == FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
+ return;
+ }
+
+ native_slot_get(intern->type, memory, return_value_ptr TSRMLS_CC);
+}
+
+/**
+ * Assign the element at the given index.
+ * This will also be called for: $arr []= $ele and $arr[0] = ele
+ * @param long The index of the element to be assigned.
+ * @param object The element to be assigned.
+ * @exception Invalid type for index.
+ * @exception Non-existing index.
+ * @exception Incorrect type of the element.
+ */
+PHP_METHOD(RepeatedField, offsetSet) {
+ zval *index, *value;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) ==
+ FAILURE) {
+ return;
+ }
+ repeated_field_write_dimension(getThis(), index, value TSRMLS_CC);
+}
+
+/**
+ * Remove the element at the given index.
+ * This will also be called for: unset($arr)
+ * @param long The index of the element to be removed.
+ * @exception Invalid type for index.
+ * @exception The element to be removed is not at the end of the RepeatedField.
+ */
+PHP_METHOD(RepeatedField, offsetUnset) {
+ long index;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ return;
+ }
+
+ RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ // Only the element at the end of the array can be removed.
+ if (index == -1 ||
+ index != (zend_hash_num_elements(HASH_OF(intern->array)) - 1)) {
+ zend_error(E_USER_ERROR, "Cannot remove element at %ld.\n", index);
+ return;
+ }
+
+ zend_hash_index_del(HASH_OF(intern->array), index);
+}
+
+/**
+ * Return the number of stored elements.
+ * This will also be called for: count($arr)
+ * @return long The number of stored elements.
+ */
+PHP_METHOD(RepeatedField, count) {
+ RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ if (zend_parse_parameters_none() == FAILURE) {
+ return;
+ }
+
+ RETURN_LONG(zend_hash_num_elements(HASH_OF(intern->array)));
+}
+
+/**
+ * Return the beginning iterator.
+ * This will also be called for: foreach($arr)
+ * @return object Beginning iterator.
+ */
+PHP_METHOD(RepeatedField, getIterator) {
+ zval *iter_php = NULL;
+ MAKE_STD_ZVAL(iter_php);
+ Z_TYPE_P(iter_php) = IS_OBJECT;
+ Z_OBJVAL_P(iter_php) = repeated_field_iter_type->create_object(
+ repeated_field_iter_type TSRMLS_CC);
+
+ RepeatedField *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedFieldIter *iter = zend_object_store_get_object(iter_php TSRMLS_CC);
+ iter->repeated_field = intern;
+ iter->position = 0;
+
+ RETURN_ZVAL(iter_php, 1, 1);
+}
+
+// -----------------------------------------------------------------------------
+// RepeatedFieldIter creation/desctruction
+// -----------------------------------------------------------------------------
+
+void repeated_field_iter_init(TSRMLS_D) {
+ zend_class_entry class_type;
+ const char* class_name = "Google\\Protobuf\\Internal\\RepeatedFieldIter";
+ INIT_CLASS_ENTRY_EX(class_type, class_name, strlen(class_name),
+ repeated_field_iter_methods);
+
+ repeated_field_iter_type =
+ zend_register_internal_class(&class_type TSRMLS_CC);
+ repeated_field_iter_type->create_object = repeated_field_iter_create;
+
+ zend_class_implements(repeated_field_iter_type TSRMLS_CC, 1,
+ zend_ce_iterator);
+}
+
+static zend_object_value repeated_field_iter_create(
+ zend_class_entry *ce TSRMLS_DC) {
+ zend_object_value retval = {0};
+ RepeatedFieldIter *intern;
+
+ intern = emalloc(sizeof(RepeatedFieldIter));
+ memset(intern, 0, sizeof(RepeatedFieldIter));
+
+ zend_object_std_init(&intern->std, ce TSRMLS_CC);
+ object_properties_init(&intern->std, ce);
+
+ intern->repeated_field = NULL;
+ intern->position = 0;
+
+ retval.handle = zend_objects_store_put(
+ intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
+ (zend_objects_free_object_storage_t)repeated_field_iter_free,
+ NULL TSRMLS_CC);
+ retval.handlers = zend_get_std_object_handlers();
+
+ return retval;
+}
+
+static void repeated_field_iter_free(void *object TSRMLS_DC) {
+ RepeatedFieldIter *intern = object;
+ zend_object_std_dtor(&intern->std TSRMLS_CC);
+ efree(object);
+}
+
+// -----------------------------------------------------------------------------
+// PHP RepeatedFieldIter Methods
+// -----------------------------------------------------------------------------
+
+PHP_METHOD(RepeatedFieldIter, rewind) {
+ RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ intern->position = 0;
+}
+
+PHP_METHOD(RepeatedFieldIter, current) {
+ RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RepeatedField *repeated_field = intern->repeated_field;
+
+ long index;
+ void *memory;
+
+ HashTable *table = HASH_OF(repeated_field->array);
+
+ if (zend_hash_index_find(table, intern->position, (void **)&memory) ==
+ FAILURE) {
+ zend_error(E_USER_ERROR, "Element at %ld doesn't exist.\n", index);
+ return;
+ }
+ native_slot_get(repeated_field->type, memory, return_value_ptr TSRMLS_CC);
+}
+
+PHP_METHOD(RepeatedFieldIter, key) {
+ RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RETURN_LONG(intern->position);
+}
+
+PHP_METHOD(RepeatedFieldIter, next) {
+ RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ ++intern->position;
+}
+
+PHP_METHOD(RepeatedFieldIter, valid) {
+ RepeatedFieldIter *intern = zend_object_store_get_object(getThis() TSRMLS_CC);
+ RETURN_BOOL(zend_hash_num_elements(HASH_OF(intern->repeated_field->array)) >
+ intern->position);
+}
diff --git a/php/ext/google/protobuf/config.m4 b/php/ext/google/protobuf/config.m4
index b5946f74..ab032e46 100644
--- a/php/ext/google/protobuf/config.m4
+++ b/php/ext/google/protobuf/config.m4
@@ -1,10 +1,10 @@
-dnl lines starting with "dnl" are comments
-
PHP_ARG_ENABLE(protobuf, whether to enable Protobuf extension, [ --enable-protobuf Enable Protobuf extension])
if test "$PHP_PROTOBUF" != "no"; then
- dnl this defines the extension
- PHP_NEW_EXTENSION(protobuf, upb.c protobuf.c def.c message.c storage.c, $ext_shared)
+ PHP_NEW_EXTENSION(
+ protobuf,
+ array.c def.c encode_decode.c map.c message.c protobuf.c storage.c type_check.c upb.c utf8.c,
+ $ext_shared)
fi
diff --git a/php/ext/google/protobuf/def.c b/php/ext/google/protobuf/def.c
index fc188069..5a8c3c25 100644
--- a/php/ext/google/protobuf/def.c
+++ b/php/ext/google/protobuf/def.c
@@ -1,115 +1,213 @@
+// 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 "protobuf.h"
+// Forward declare.
+static zend_object_value descriptor_create(zend_class_entry *ce TSRMLS_DC);
+static void descriptor_init_c_instance(Descriptor* intern TSRMLS_DC);
+static void descriptor_free_c(Descriptor* object TSRMLS_DC);
+static void descriptor_free(void* object TSRMLS_DC);
+
+static zend_object_value enum_descriptor_create(zend_class_entry *ce TSRMLS_DC);
+static void enum_descriptor_init_c_instance(EnumDescriptor* intern TSRMLS_DC);
+static void enum_descriptor_free_c(EnumDescriptor* object TSRMLS_DC);
+static void enum_descriptor_free(void* object TSRMLS_DC);
+
+static zend_object_value descriptor_pool_create(zend_class_entry *ce TSRMLS_DC);
+static void descriptor_pool_free_c(DescriptorPool* object TSRMLS_DC);
+static void descriptor_pool_free(void* object TSRMLS_DC);
+static void descriptor_pool_init_c_instance(DescriptorPool* pool TSRMLS_DC);
+
// -----------------------------------------------------------------------------
// Common Utilities
// -----------------------------------------------------------------------------
-void check_upb_status(const upb_status* status, const char* msg) {
+static void check_upb_status(const upb_status* status, const char* msg) {
if (!upb_ok(status)) {
- zend_error("%s: %s\n", msg, upb_status_errmsg(status));
+ zend_error(E_ERROR, "%s: %s\n", msg, upb_status_errmsg(status));
}
}
+static void upb_filedef_free(void *r) {
+ upb_filedef *f = *(upb_filedef **)r;
+ size_t i;
-static upb_def *check_notfrozen(const upb_def *def) {
- if (upb_def_isfrozen(def)) {
- zend_error(E_ERROR,
- "Attempt to modify a frozen descriptor. Once descriptors are "
- "added to the descriptor pool, they may not be modified.");
+ for (i = 0; i < upb_filedef_depcount(f); i++) {
+ upb_filedef_unref(upb_filedef_dep(f, i), f);
}
- return (upb_def *)def;
-}
-static upb_msgdef *check_msgdef_notfrozen(const upb_msgdef *def) {
- return upb_downcast_msgdef_mutable(check_notfrozen((const upb_def *)def));
+ upb_inttable_uninit(&f->defs);
+ upb_inttable_uninit(&f->deps);
+ upb_gfree((void *)f->name);
+ upb_gfree((void *)f->package);
+ upb_gfree(f);
}
-static upb_fielddef *check_fielddef_notfrozen(const upb_fielddef *def) {
- return upb_downcast_fielddef_mutable(check_notfrozen((const upb_def *)def));
+// Camel-case the field name and append "Entry" for generated map entry name.
+// e.g. map<KeyType, ValueType> foo_map => FooMapEntry
+static void append_map_entry_name(char *result, const char *field_name,
+ int pos) {
+ bool cap_next = true;
+ int i;
+
+ for (i = 0; i < strlen(field_name); ++i) {
+ if (field_name[i] == '_') {
+ cap_next = true;
+ } else if (cap_next) {
+ // Note: Do not use ctype.h due to locales.
+ if ('a' <= field_name[i] && field_name[i] <= 'z') {
+ result[pos++] = field_name[i] - 'a' + 'A';
+ } else {
+ result[pos++] = field_name[i];
+ }
+ cap_next = false;
+ } else {
+ result[pos++] = field_name[i];
+ }
+ }
+ strcat(result, "Entry");
}
-#define PROTOBUF_WRAP_INTERN(wrapper, intern, intern_dtor) \
- Z_TYPE_P(wrapper) = IS_OBJECT; \
- Z_OBJVAL_P(wrapper) \
- .handle = zend_objects_store_put( \
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, \
- intern_dtor, NULL TSRMLS_CC); \
- Z_OBJVAL_P(wrapper).handlers = zend_get_std_object_handlers();
-
-#define PROTOBUF_SETUP_ZEND_WRAPPER(class_name, class_name_lower, wrapper, \
- intern) \
- Z_TYPE_P(wrapper) = IS_OBJECT; \
- class_name *intern = ALLOC(class_name); \
- memset(intern, 0, sizeof(class_name)); \
- class_name_lower##_init_c_instance(intern TSRMLS_CC); \
- Z_OBJVAL_P(wrapper) \
- .handle = zend_objects_store_put(intern, NULL, class_name_lower##_free, \
- NULL TSRMLS_CC); \
- Z_OBJVAL_P(wrapper).handlers = zend_get_std_object_handlers();
-
-#define PROTOBUF_CREATE_ZEND_WRAPPER(class_name, class_name_lower, wrapper, \
- intern) \
- MAKE_STD_ZVAL(wrapper); \
- PROTOBUF_SETUP_ZEND_WRAPPER(class_name, class_name_lower, wrapper, intern);
-
-#define DEFINE_CLASS(name, name_lower, string_name) \
- zend_class_entry *name_lower##_type; \
+#define CHECK_UPB(code, msg) \
+ do { \
+ upb_status status = UPB_STATUS_INIT; \
+ code; \
+ check_upb_status(&status, msg); \
+ } while (0)
+
+// Define PHP class
+#define DEFINE_PROTOBUF_INIT_CLASS(name_lower, string_name) \
void name_lower##_init(TSRMLS_D) { \
zend_class_entry class_type; \
INIT_CLASS_ENTRY(class_type, string_name, name_lower##_methods); \
name_lower##_type = zend_register_internal_class(&class_type TSRMLS_CC); \
name_lower##_type->create_object = name_lower##_create; \
- } \
- name *php_to_##name_lower(zval *val TSRMLS_DC) { \
- return (name *)zend_object_store_get_object(val TSRMLS_CC); \
- } \
- void name_lower##_free(void *object TSRMLS_DC) { \
- name *intern = (name *)object; \
- name_lower##_free_c(intern TSRMLS_CC); \
- efree(object); \
- } \
- zend_object_value name_lower##_create(zend_class_entry *ce TSRMLS_DC) { \
- zend_object_value return_value; \
- name *intern = (name *)emalloc(sizeof(name)); \
- memset(intern, 0, sizeof(name)); \
- name_lower##_init_c_instance(intern TSRMLS_CC); \
- return_value.handle = zend_objects_store_put( \
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, \
- name_lower##_free, NULL TSRMLS_CC); \
- return_value.handlers = zend_get_std_object_handlers(); \
- return return_value; \
}
+#define DEFINE_PROTOBUF_CREATE(name, name_lower) \
+ static zend_object_value name_lower##_create( \
+ zend_class_entry* ce TSRMLS_DC) { \
+ zend_object_value return_value; \
+ name* intern = (name*)emalloc(sizeof(name)); \
+ memset(intern, 0, sizeof(name)); \
+ name_lower##_init_c_instance(intern TSRMLS_CC); \
+ return_value.handle = zend_objects_store_put( \
+ intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, \
+ name_lower##_free, NULL TSRMLS_CC); \
+ return_value.handlers = zend_get_std_object_handlers(); \
+ return return_value; \
+ }
+
+#define DEFINE_PROTOBUF_FREE(name, name_lower) \
+ static void name_lower##_free(void* object TSRMLS_DC) { \
+ name* intern = (name*)object; \
+ name_lower##_free_c(intern TSRMLS_CC); \
+ efree(object); \
+ }
+
+#define DEFINE_CLASS(name, name_lower, string_name) \
+ zend_class_entry* name_lower##_type; \
+ DEFINE_PROTOBUF_FREE(name, name_lower) \
+ DEFINE_PROTOBUF_CREATE(name, name_lower) \
+ DEFINE_PROTOBUF_INIT_CLASS(name_lower, string_name)
+
+// -----------------------------------------------------------------------------
+// GPBType
+// -----------------------------------------------------------------------------
+
+zend_class_entry* gpb_type_type;
+
+static zend_function_entry gpb_type_methods[] = {
+ ZEND_FE_END
+};
+
+void gpb_type_init(TSRMLS_D) {
+ zend_class_entry class_type;
+ INIT_CLASS_ENTRY(class_type, "Google\\Protobuf\\Internal\\GPBType",
+ gpb_type_methods);
+ gpb_type_type = zend_register_internal_class(&class_type TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("DOUBLE"), 1 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("FLOAT"), 2 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("INT64"), 3 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("UINT64"), 4 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("INT32"), 5 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("FIXED64"), 6 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("FIXED32"), 7 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("BOOL"), 8 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("STRING"), 9 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("GROUP"), 10 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("MESSAGE"), 11 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("BYTES"), 12 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("UINT32"), 13 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("ENUM"), 14 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("SFIXED32"),
+ 15 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("SFIXED64"),
+ 16 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("SINT32"), 17 TSRMLS_CC);
+ zend_declare_class_constant_long(gpb_type_type, STR("SINT64"), 18 TSRMLS_CC);
+}
+
// -----------------------------------------------------------------------------
// DescriptorPool
// -----------------------------------------------------------------------------
static zend_function_entry descriptor_pool_methods[] = {
- PHP_ME(DescriptorPool, addMessage, NULL, ZEND_ACC_PUBLIC)
- PHP_ME(DescriptorPool, finalize, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(DescriptorPool, getGeneratedPool, NULL,
+ ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(DescriptorPool, internalAddGeneratedFile, NULL, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
DEFINE_CLASS(DescriptorPool, descriptor_pool,
- "Google\\Protobuf\\DescriptorPool");
+ "Google\\Protobuf\\Internal\\DescriptorPool");
+zval* generated_pool_php; // wrapper of generated pool
DescriptorPool *generated_pool; // The actual generated pool
-ZEND_FUNCTION(get_generated_pool) {
- if (PROTOBUF_G(generated_pool) == NULL) {
- MAKE_STD_ZVAL(PROTOBUF_G(generated_pool));
- Z_TYPE_P(PROTOBUF_G(generated_pool)) = IS_OBJECT;
+static void init_generated_pool_once(TSRMLS_D) {
+ if (generated_pool_php == NULL) {
+ MAKE_STD_ZVAL(generated_pool_php);
+ Z_TYPE_P(generated_pool_php) = IS_OBJECT;
generated_pool = ALLOC(DescriptorPool);
descriptor_pool_init_c_instance(generated_pool TSRMLS_CC);
- Z_OBJ_HANDLE_P(PROTOBUF_G(generated_pool)) = zend_objects_store_put(
+ Z_OBJ_HANDLE_P(generated_pool_php) = zend_objects_store_put(
generated_pool, NULL,
- (zend_objects_free_object_storage_t)descriptor_pool_free, NULL TSRMLS_CC);
- Z_OBJ_HT_P(PROTOBUF_G(generated_pool)) = zend_get_std_object_handlers();
+ (zend_objects_free_object_storage_t)descriptor_pool_free,
+ NULL TSRMLS_CC);
+ Z_OBJ_HT_P(generated_pool_php) = zend_get_std_object_handlers();
}
- RETURN_ZVAL(PROTOBUF_G(generated_pool), 1, 0);
}
-void descriptor_pool_init_c_instance(DescriptorPool* pool TSRMLS_DC) {
+static void descriptor_pool_init_c_instance(DescriptorPool *pool TSRMLS_DC) {
zend_object_std_init(&pool->std, descriptor_pool_type TSRMLS_CC);
pool->symtab = upb_symtab_new(&pool->symtab);
@@ -117,31 +215,21 @@ void descriptor_pool_init_c_instance(DescriptorPool* pool TSRMLS_DC) {
zend_hash_init(pool->pending_list, 1, NULL, ZVAL_PTR_DTOR, 0);
}
-void descriptor_pool_free_c(DescriptorPool *pool TSRMLS_DC) {
+static void descriptor_pool_free_c(DescriptorPool *pool TSRMLS_DC) {
upb_symtab_unref(pool->symtab, &pool->symtab);
+
zend_hash_destroy(pool->pending_list);
FREE_HASHTABLE(pool->pending_list);
}
-PHP_METHOD(DescriptorPool, addMessage) {
- char *name = NULL;
- int str_len;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &str_len) ==
- FAILURE) {
- return;
+static void validate_enumdef(const upb_enumdef *enumdef) {
+ // Verify that an entry exists with integer value 0. (This is the default
+ // value.)
+ const char *lookup = upb_enumdef_iton(enumdef, 0);
+ if (lookup == NULL) {
+ zend_error(E_USER_ERROR,
+ "Enum definition does not contain a value for '0'.");
}
-
- zval* retval = NULL;
- PROTOBUF_CREATE_ZEND_WRAPPER(MessageBuilderContext, message_builder_context,
- retval, context);
-
- MAKE_STD_ZVAL(context->pool);
- ZVAL_ZVAL(context->pool, getThis(), 1, 0);
-
- Descriptor *desc = php_to_descriptor(context->descriptor TSRMLS_CC);
- Descriptor_name_set(desc, name);
-
- RETURN_ZVAL(retval, 0, 1);
}
static void validate_msgdef(const upb_msgdef* msgdef) {
@@ -157,35 +245,130 @@ static void validate_msgdef(const upb_msgdef* msgdef) {
}
}
-PHP_METHOD(DescriptorPool, finalize) {
- DescriptorPool *self = php_to_descriptor_pool(getThis() TSRMLS_CC);
- Bucket *temp;
- int i, num;
+PHP_METHOD(DescriptorPool, getGeneratedPool) {
+ init_generated_pool_once(TSRMLS_C);
+ RETURN_ZVAL(generated_pool_php, 1, 0);
+}
+
+static void convert_to_class_name_inplace(char *class_name,
+ const char* fullname,
+ const char* package_name) {
+ size_t i;
+ bool first_char = false;
+ size_t pkg_name_len = package_name == NULL ? 0 : strlen(package_name);
+
+ if (pkg_name_len == 0) {
+ strcpy(class_name, fullname);
+ } else {
+ class_name[0] = '.';
+ strcpy(&class_name[1], fullname);
+ for (i = 0; i <= pkg_name_len + 1; i++) {
+ // PHP package uses camel case.
+ if (!first_char && class_name[i] != '.') {
+ first_char = true;
+ class_name[i] += 'A' - 'a';
+ }
+ // php packages are divided by '\'.
+ if (class_name[i] == '.') {
+ first_char = false;
+ class_name[i] = '\\';
+ }
+ }
+ }
+
+ // Submessage is concatenated with its containing messages by '_'.
+ for (i = pkg_name_len; i < strlen(class_name); i++) {
+ if (class_name[i] == '.') {
+ class_name[i] = '_';
+ }
+ }
+}
+
+PHP_METHOD(DescriptorPool, internalAddGeneratedFile) {
+ char *data = NULL;
+ int data_len;
+ upb_filedef **files;
+ size_t i;
- num = zend_hash_num_elements(self->pending_list);
- upb_def **defs = emalloc(sizeof(upb_def *) * num);
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
+ FAILURE) {
+ return;
+ }
- for (i = 0, temp = self->pending_list->pListHead; temp != NULL;
- temp = temp->pListNext) {
- zval *def_php = *(zval **)temp->pData;
- Descriptor* desc = php_to_descriptor(def_php TSRMLS_CC);
- defs[i] = (upb_def *)desc->msgdef;
- validate_msgdef((const upb_msgdef *)defs[i++]);
+ DescriptorPool *pool = UNBOX(DescriptorPool, getThis());
+ CHECK_UPB(files = upb_loaddescriptor(data, data_len, &pool, &status),
+ "Parse binary descriptors to internal descriptors failed");
+
+ // This method is called only once in each file.
+ assert(files[0] != NULL);
+ assert(files[1] == NULL);
+
+ CHECK_UPB(upb_symtab_addfile(pool->symtab, files[0], &status),
+ "Unable to add file to DescriptorPool");
+
+ // For each enum/message, we need its PHP class, upb descriptor and its PHP
+ // wrapper. These information are needed later for encoding, decoding and type
+ // checking. However, sometimes we just have one of them. In order to find
+ // them quickly, here, we store the mapping for them.
+ for (i = 0; i < upb_filedef_defcount(files[0]); i++) {
+ const upb_def *def = upb_filedef_def(files[0], i);
+ switch (upb_def_type(def)) {
+#define CASE_TYPE(def_type, def_type_lower, desc_type, desc_type_lower) \
+ case UPB_DEF_##def_type: { \
+ desc_type *desc; \
+ zval *desc_php; \
+ CREATE(desc_type, desc, desc_type_lower##_init_c_instance); \
+ BOX(desc_type, desc_php, desc, desc_type_lower##_free); \
+ Z_DELREF_P(desc_php); \
+ const upb_##def_type_lower *def_type_lower = \
+ upb_downcast_##def_type_lower(def); \
+ desc->def_type_lower = def_type_lower; \
+ add_def_obj(desc->def_type_lower, desc_php); \
+ /* Unlike other messages, MapEntry is shared by all map fields and doesn't \
+ * have generated PHP class.*/ \
+ if (upb_def_type(def) == UPB_DEF_MSG && \
+ upb_msgdef_mapentry(upb_downcast_msgdef(def))) { \
+ break; \
+ } \
+ /* Prepend '.' to package name to make it absolute. */ \
+ const char *fullname = upb_##def_type_lower##_fullname(def_type_lower); \
+ char *klass_name = ecalloc(sizeof(char), 2 + strlen(fullname)); \
+ convert_to_class_name_inplace(klass_name, fullname, \
+ upb_filedef_package(files[0])); \
+ zend_class_entry **pce; \
+ if (zend_lookup_class(klass_name, strlen(klass_name), &pce TSRMLS_CC) == \
+ FAILURE) { \
+ zend_error(E_ERROR, "Generated message class %s hasn't been defined", \
+ klass_name); \
+ return; \
+ } else { \
+ desc->klass = *pce; \
+ } \
+ add_ce_obj(desc->klass, desc_php); \
+ efree(klass_name); \
+ break; \
}
- CHECK_UPB(upb_symtab_add(self->symtab, (upb_def **)defs, num, NULL, &status),
- "Unable to add defs to DescriptorPool");
+ CASE_TYPE(MSG, msgdef, Descriptor, descriptor)
+ CASE_TYPE(ENUM, enumdef, EnumDescriptor, enum_descriptor)
+#undef CASE_TYPE
- for (temp = self->pending_list->pListHead; temp != NULL;
- temp = temp->pListNext) {
- // zval *def_php = *(zval **)temp->pData;
- // Descriptor* desc = php_to_descriptor(def_php TSRMLS_CC);
- build_class_from_descriptor((zval *)temp->pDataPtr TSRMLS_CC);
+ default:
+ break;
+ }
}
- FREE(defs);
- zend_hash_destroy(self->pending_list);
- zend_hash_init(self->pending_list, 1, NULL, ZVAL_PTR_DTOR, 0);
+ for (i = 0; i < upb_filedef_defcount(files[0]); i++) {
+ const upb_def *def = upb_filedef_def(files[0], i);
+ if (upb_def_type(def) == UPB_DEF_MSG) {
+ const upb_msgdef *msgdef = upb_downcast_msgdef(def);
+ zval *desc_php = get_def_obj(msgdef);
+ build_class_from_descriptor(desc_php TSRMLS_CC);
+ }
+ }
+
+ upb_filedef_unref(files[0], &pool);
+ upb_gfree(files);
}
// -----------------------------------------------------------------------------
@@ -196,186 +379,87 @@ static zend_function_entry descriptor_methods[] = {
ZEND_FE_END
};
-DEFINE_CLASS(Descriptor, descriptor, "Google\\Protobuf\\Descriptor");
+DEFINE_CLASS(Descriptor, descriptor, "Google\\Protobuf\\Internal\\Descriptor");
-void descriptor_free_c(Descriptor *self TSRMLS_DC) {
- upb_msg_field_iter iter;
- upb_msg_field_begin(&iter, self->msgdef);
- while (!upb_msg_field_done(&iter)) {
- upb_fielddef *fielddef = upb_msg_iter_field(&iter);
- upb_fielddef_unref(fielddef, &fielddef);
- upb_msg_field_next(&iter);
- }
- upb_msgdef_unref(self->msgdef, &self->msgdef);
+static void descriptor_free_c(Descriptor *self TSRMLS_DC) {
if (self->layout) {
free_layout(self->layout);
}
+ if (self->fill_handlers) {
+ upb_handlers_unref(self->fill_handlers, &self->fill_handlers);
+ }
+ if (self->fill_method) {
+ upb_pbdecodermethod_unref(self->fill_method, &self->fill_method);
+ }
+ if (self->pb_serialize_handlers) {
+ upb_handlers_unref(self->pb_serialize_handlers,
+ &self->pb_serialize_handlers);
+ }
}
-static void descriptor_add_field(Descriptor *desc,
- const upb_fielddef *fielddef) {
- upb_msgdef *mut_def = check_msgdef_notfrozen(desc->msgdef);
- upb_fielddef *mut_field_def = check_fielddef_notfrozen(fielddef);
- CHECK_UPB(upb_msgdef_addfield(mut_def, mut_field_def, NULL, &status),
- "Adding field to Descriptor failed");
- // add_def_obj(fielddef, obj);
-}
-
-void descriptor_init_c_instance(Descriptor* desc TSRMLS_DC) {
+static void descriptor_init_c_instance(Descriptor *desc TSRMLS_DC) {
zend_object_std_init(&desc->std, descriptor_type TSRMLS_CC);
- desc->msgdef = upb_msgdef_new(&desc->msgdef);
+ desc->msgdef = NULL;
desc->layout = NULL;
- // MAKE_STD_ZVAL(intern->klass);
- // ZVAL_NULL(intern->klass);
+ desc->klass = NULL;
+ desc->fill_handlers = NULL;
+ desc->fill_method = NULL;
desc->pb_serialize_handlers = NULL;
}
-void Descriptor_name_set(Descriptor *desc, const char *name) {
- upb_msgdef *mut_def = check_msgdef_notfrozen(desc->msgdef);
- CHECK_UPB(upb_msgdef_setfullname(mut_def, name, &status),
- "Error setting Descriptor name");
-}
-
// -----------------------------------------------------------------------------
-// FieldDescriptor
+// EnumDescriptor
// -----------------------------------------------------------------------------
-static void field_descriptor_name_set(const upb_fielddef* fielddef,
- const char *name) {
- upb_fielddef *mut_def = check_fielddef_notfrozen(fielddef);
- CHECK_UPB(upb_fielddef_setname(mut_def, name, &status),
- "Error setting FieldDescriptor name");
-}
-
-static void field_descriptor_label_set(const upb_fielddef* fielddef,
- upb_label_t upb_label) {
- upb_fielddef *mut_def = check_fielddef_notfrozen(fielddef);
- upb_fielddef_setlabel(mut_def, upb_label);
-}
-
-upb_fieldtype_t string_to_descriptortype(const char *type) {
-#define CONVERT(upb, str) \
- if (!strcmp(type, str)) { \
- return UPB_DESCRIPTOR_TYPE_##upb; \
- }
+static zend_function_entry enum_descriptor_methods[] = {
+ ZEND_FE_END
+};
- CONVERT(FLOAT, "float");
- CONVERT(DOUBLE, "double");
- CONVERT(BOOL, "bool");
- CONVERT(STRING, "string");
- CONVERT(BYTES, "bytes");
- CONVERT(MESSAGE, "message");
- CONVERT(GROUP, "group");
- CONVERT(ENUM, "enum");
- CONVERT(INT32, "int32");
- CONVERT(INT64, "int64");
- CONVERT(UINT32, "uint32");
- CONVERT(UINT64, "uint64");
- CONVERT(SINT32, "sint32");
- CONVERT(SINT64, "sint64");
- CONVERT(FIXED32, "fixed32");
- CONVERT(FIXED64, "fixed64");
- CONVERT(SFIXED32, "sfixed32");
- CONVERT(SFIXED64, "sfixed64");
+DEFINE_CLASS(EnumDescriptor, enum_descriptor,
+ "Google\\Protobuf\\Internal\\EnumDescriptor");
-#undef CONVERT
-
- zend_error(E_ERROR, "Unknown field type.");
- return 0;
-}
-
-static void field_descriptor_type_set(const upb_fielddef* fielddef,
- const char *type) {
- upb_fielddef *mut_def = check_fielddef_notfrozen(fielddef);
- upb_fielddef_setdescriptortype(mut_def, string_to_descriptortype(type));
+static void enum_descriptor_free_c(EnumDescriptor *self TSRMLS_DC) {
}
-static void field_descriptor_number_set(const upb_fielddef* fielddef,
- int number) {
- upb_fielddef *mut_def = check_fielddef_notfrozen(fielddef);
- CHECK_UPB(upb_fielddef_setnumber(mut_def, number, &status),
- "Error setting field number");
+static void enum_descriptor_init_c_instance(EnumDescriptor *self TSRMLS_DC) {
+ zend_object_std_init(&self->std, enum_descriptor_type TSRMLS_CC);
+ self->enumdef = NULL;
+ self->klass = NULL;
}
// -----------------------------------------------------------------------------
-// MessageBuilderContext
+// FieldDescriptor
// -----------------------------------------------------------------------------
-static zend_function_entry message_builder_context_methods[] = {
- PHP_ME(MessageBuilderContext, finalizeToPool, NULL, ZEND_ACC_PUBLIC)
- PHP_ME(MessageBuilderContext, optional, NULL, ZEND_ACC_PUBLIC)
- {NULL, NULL, NULL}
-};
-
-DEFINE_CLASS(MessageBuilderContext, message_builder_context,
- "Google\\Protobuf\\Internal\\MessageBuilderContext");
+upb_fieldtype_t to_fieldtype(upb_descriptortype_t type) {
+ switch (type) {
+#define CASE(descriptor_type, type) \
+ case UPB_DESCRIPTOR_TYPE_##descriptor_type: \
+ return UPB_TYPE_##type;
+
+ CASE(FLOAT, FLOAT);
+ CASE(DOUBLE, DOUBLE);
+ CASE(BOOL, BOOL);
+ CASE(STRING, STRING);
+ CASE(BYTES, BYTES);
+ CASE(MESSAGE, MESSAGE);
+ CASE(GROUP, MESSAGE);
+ CASE(ENUM, ENUM);
+ CASE(INT32, INT32);
+ CASE(INT64, INT64);
+ CASE(UINT32, UINT32);
+ CASE(UINT64, UINT64);
+ CASE(SINT32, INT32);
+ CASE(SINT64, INT64);
+ CASE(FIXED32, UINT32);
+ CASE(FIXED64, UINT64);
+ CASE(SFIXED32, INT32);
+ CASE(SFIXED64, INT64);
-void message_builder_context_free_c(MessageBuilderContext *context TSRMLS_DC) {
- zval_ptr_dtor(&context->descriptor);
- zval_ptr_dtor(&context->pool);
-}
-
-void message_builder_context_init_c_instance(
- MessageBuilderContext *context TSRMLS_DC) {
- zend_object_std_init(&context->std, message_builder_context_type TSRMLS_CC);
- PROTOBUF_CREATE_ZEND_WRAPPER(Descriptor, descriptor, context->descriptor,
- desc);
-}
-
-static void msgdef_add_field(Descriptor *desc, upb_label_t upb_label,
- const char *name, const char *type, int number,
- const char *type_class) {
- upb_fielddef *fielddef = upb_fielddef_new(&fielddef);
- upb_fielddef_setpacked(fielddef, false);
-
- field_descriptor_label_set(fielddef, upb_label);
- field_descriptor_name_set(fielddef, name);
- field_descriptor_type_set(fielddef, type);
- field_descriptor_number_set(fielddef, number);
-
-// // if (type_class != Qnil) {
-// // if (TYPE(type_class) != T_STRING) {
-// // rb_raise(rb_eArgError, "Expected string for type class");
-// // }
-// // // Make it an absolute type name by prepending a dot.
-// // type_class = rb_str_append(rb_str_new2("."), type_class);
-// // rb_funcall(fielddef, rb_intern("submsg_name="), 1, type_class);
-// // }
- descriptor_add_field(desc, fielddef);
-}
+#undef CONVERT
-PHP_METHOD(MessageBuilderContext, optional) {
- MessageBuilderContext *self = php_to_message_builder_context(getThis() TSRMLS_CC);
- Descriptor *desc = php_to_descriptor(self->descriptor TSRMLS_CC);
- // VALUE name, type, number, type_class;
- const char *name, *type, *type_class;
- int number, name_str_len, type_str_len, type_class_str_len;
- if (ZEND_NUM_ARGS() == 3) {
- if (zend_parse_parameters(3 TSRMLS_CC, "ssl", &name,
- &name_str_len, &type, &type_str_len, &number) == FAILURE) {
- return;
- }
- } else {
- if (zend_parse_parameters(4 TSRMLS_CC, "ssls", &name,
- &name_str_len, &type, &type_str_len, &number, &type_class,
- &type_class_str_len) == FAILURE) {
- return;
- }
}
- msgdef_add_field(desc, UPB_LABEL_OPTIONAL, name, type, number, type_class);
-
- zval_copy_ctor(getThis());
- RETURN_ZVAL(getThis(), 1, 0);
-}
-
-PHP_METHOD(MessageBuilderContext, finalizeToPool) {
- MessageBuilderContext *self = php_to_message_builder_context(getThis() TSRMLS_CC);
- DescriptorPool *pool = php_to_descriptor_pool(self->pool TSRMLS_CC);
- Descriptor* desc = php_to_descriptor(self->descriptor TSRMLS_CC);
-
- Z_ADDREF_P(self->descriptor);
- zend_hash_next_index_insert(pool->pending_list, &self->descriptor,
- sizeof(zval *), NULL);
- RETURN_ZVAL(self->pool, 1, 0);
+ zend_error(E_ERROR, "Unknown field type.");
+ return 0;
}
diff --git a/php/ext/google/protobuf/encode_decode.c b/php/ext/google/protobuf/encode_decode.c
new file mode 100644
index 00000000..eafe1ae8
--- /dev/null
+++ b/php/ext/google/protobuf/encode_decode.c
@@ -0,0 +1,1257 @@
+// 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 "protobuf.h"
+#include "utf8.h"
+
+/* stringsink *****************************************************************/
+
+typedef struct {
+ upb_byteshandler handler;
+ upb_bytessink sink;
+ char *ptr;
+ size_t len, size;
+} stringsink;
+
+
+static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
+ stringsink *sink = _sink;
+ sink->len = 0;
+ return sink;
+}
+
+static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
+ size_t len, const upb_bufhandle *handle) {
+ stringsink *sink = _sink;
+ size_t new_size = sink->size;
+
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ while (sink->len + len > new_size) {
+ new_size *= 2;
+ }
+
+ if (new_size != sink->size) {
+ sink->ptr = realloc(sink->ptr, new_size);
+ sink->size = new_size;
+ }
+
+ memcpy(sink->ptr + sink->len, ptr, len);
+ sink->len += len;
+
+ return len;
+}
+
+void stringsink_init(stringsink *sink) {
+ upb_byteshandler_init(&sink->handler);
+ upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
+ upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
+
+ upb_bytessink_reset(&sink->sink, &sink->handler, sink);
+
+ sink->size = 32;
+ sink->ptr = malloc(sink->size);
+ sink->len = 0;
+}
+
+void stringsink_uninit(stringsink *sink) { free(sink->ptr); }
+
+/* stackenv *****************************************************************/
+
+// Stack-allocated context during an encode/decode operation. Contains the upb
+// environment and its stack-based allocator, an initial buffer for allocations
+// to avoid malloc() when possible, and a template for PHP exception messages
+// if any error occurs.
+#define STACK_ENV_STACKBYTES 4096
+typedef struct {
+ upb_env env;
+ const char *php_error_template;
+ char allocbuf[STACK_ENV_STACKBYTES];
+} stackenv;
+
+
+static void stackenv_init(stackenv* se, const char* errmsg);
+static void stackenv_uninit(stackenv* se);
+
+// Callback invoked by upb if any error occurs during parsing or serialization.
+static bool env_error_func(void* ud, const upb_status* status) {
+ stackenv* se = ud;
+ // Free the env -- zend_error will longjmp up the stack past the
+ // encode/decode function so it would not otherwise have been freed.
+ stackenv_uninit(se);
+
+ // TODO(teboring): have a way to verify that this is actually a parse error,
+ // instead of just throwing "parse error" unconditionally.
+ zend_error(E_ERROR, se->php_error_template, upb_status_errmsg(status));
+ // Never reached.
+ return false;
+}
+
+static void stackenv_init(stackenv* se, const char* errmsg) {
+ se->php_error_template = errmsg;
+ upb_env_init2(&se->env, se->allocbuf, sizeof(se->allocbuf), NULL);
+ upb_env_seterrorfunc(&se->env, env_error_func, se);
+}
+
+static void stackenv_uninit(stackenv* se) {
+ upb_env_uninit(&se->env);
+}
+
+// -----------------------------------------------------------------------------
+// Parsing.
+// -----------------------------------------------------------------------------
+
+#define DEREF(msg, ofs, type) *(type*)(((uint8_t *)msg) + ofs)
+
+// Creates a handlerdata that simply contains the offset for this field.
+static const void* newhandlerdata(upb_handlers* h, uint32_t ofs) {
+ size_t* hd_ofs = (size_t*)malloc(sizeof(size_t));
+ *hd_ofs = ofs;
+ upb_handlers_addcleanup(h, hd_ofs, free);
+ return hd_ofs;
+}
+
+typedef struct {
+ size_t ofs;
+ const upb_msgdef *md;
+} submsg_handlerdata_t;
+
+// Creates a handlerdata that contains offset and submessage type information.
+static const void *newsubmsghandlerdata(upb_handlers* h, uint32_t ofs,
+ const upb_fielddef* f) {
+ submsg_handlerdata_t* hd =
+ (submsg_handlerdata_t*)malloc(sizeof(submsg_handlerdata_t));
+ hd->ofs = ofs;
+ hd->md = upb_fielddef_msgsubdef(f);
+ upb_handlers_addcleanup(h, hd, free);
+ return hd;
+}
+
+typedef struct {
+ size_t ofs; // union data slot
+ size_t case_ofs; // oneof_case field
+ int property_ofs; // properties table cache
+ uint32_t oneof_case_num; // oneof-case number to place in oneof_case field
+ const upb_msgdef *md; // msgdef, for oneof submessage handler
+} oneof_handlerdata_t;
+
+static const void *newoneofhandlerdata(upb_handlers *h,
+ uint32_t ofs,
+ uint32_t case_ofs,
+ int property_ofs,
+ const upb_fielddef *f) {
+ oneof_handlerdata_t* hd =
+ (oneof_handlerdata_t*)malloc(sizeof(oneof_handlerdata_t));
+ hd->ofs = ofs;
+ hd->case_ofs = case_ofs;
+ hd->property_ofs = property_ofs;
+ // We reuse the field tag number as a oneof union discriminant tag. Note that
+ // we don't expose these numbers to the user, so the only requirement is that
+ // we have some unique ID for each union case/possibility. The field tag
+ // numbers are already present and are easy to use so there's no reason to
+ // create a separate ID space. In addition, using the field tag number here
+ // lets us easily look up the field in the oneof accessor.
+ hd->oneof_case_num = upb_fielddef_number(f);
+ if (upb_fielddef_type(f) == UPB_TYPE_MESSAGE) {
+ hd->md = upb_fielddef_msgsubdef(f);
+ } else {
+ hd->md = NULL;
+ }
+ upb_handlers_addcleanup(h, hd, free);
+ return hd;
+}
+
+// A handler that starts a repeated field. Gets the Repeated*Field instance for
+// this field (such an instance always exists even in an empty message).
+static void *startseq_handler(void* closure, const void* hd) {
+ MessageHeader* msg = closure;
+ const size_t *ofs = hd;
+ return (void*)(*DEREF(msg, *ofs, zval**));
+}
+
+// Handlers that append primitive values to a repeated field.
+#define DEFINE_APPEND_HANDLER(type, ctype) \
+ static bool append##type##_handler(void* closure, const void* hd, \
+ ctype val) { \
+ zval* array = (zval*)closure; \
+ TSRMLS_FETCH(); \
+ RepeatedField* intern = \
+ (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC); \
+ repeated_field_push_native(intern, &val TSRMLS_CC); \
+ return true; \
+ }
+
+DEFINE_APPEND_HANDLER(bool, bool)
+DEFINE_APPEND_HANDLER(int32, int32_t)
+DEFINE_APPEND_HANDLER(uint32, uint32_t)
+DEFINE_APPEND_HANDLER(float, float)
+DEFINE_APPEND_HANDLER(int64, int64_t)
+DEFINE_APPEND_HANDLER(uint64, uint64_t)
+DEFINE_APPEND_HANDLER(double, double)
+
+// Appends a string to a repeated field.
+static void* appendstr_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
+ zval* array = (zval*)closure;
+ TSRMLS_FETCH();
+ RepeatedField* intern =
+ (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+
+ zval* str;
+ MAKE_STD_ZVAL(str);
+ ZVAL_STRING(str, "", 1);
+
+ repeated_field_push_native(intern, &str TSRMLS_CC);
+ return (void*)str;
+}
+
+// Appends a 'bytes' string to a repeated field.
+static void* appendbytes_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
+ zval* array = (zval*)closure;
+ TSRMLS_FETCH();
+ RepeatedField* intern =
+ (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+
+ zval* str;
+ MAKE_STD_ZVAL(str);
+ ZVAL_STRING(str, "", 1);
+
+ repeated_field_push_native(intern, &str TSRMLS_CC);
+ return (void*)str;
+}
+
+static void *empty_php_string(zval** value_ptr) {
+ SEPARATE_ZVAL_IF_NOT_REF(value_ptr);
+ zval* str = *value_ptr;
+ zval_dtor(str);
+ ZVAL_STRINGL(str, "", 0, 1);
+ return (void*)str;
+}
+
+// Sets a non-repeated string field in a message.
+static void* str_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
+ MessageHeader* msg = closure;
+ const size_t *ofs = hd;
+ return empty_php_string(DEREF(msg, *ofs, zval**));
+}
+
+// Sets a non-repeated 'bytes' field in a message.
+static void* bytes_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
+ MessageHeader* msg = closure;
+ const size_t *ofs = hd;
+ return empty_php_string(DEREF(msg, *ofs, zval**));
+}
+
+static size_t stringdata_handler(void* closure, const void* hd,
+ const char* str, size_t len,
+ const upb_bufhandle* handle) {
+ zval* php_str = (zval*)closure;
+
+ char* old_str = Z_STRVAL_P(php_str);
+ size_t old_len = Z_STRLEN_P(php_str);
+ assert(old_str != NULL);
+
+ char* new_str = emalloc(old_len + len + 1);
+
+ memcpy(new_str, old_str, old_len);
+ memcpy(new_str + old_len, str, len);
+ new_str[old_len + len] = 0;
+ FREE(old_str);
+
+ Z_STRVAL_P(php_str) = new_str;
+ Z_STRLEN_P(php_str) = old_len + len;
+
+ return len;
+}
+
+// Appends a submessage to a repeated field.
+static void *appendsubmsg_handler(void *closure, const void *hd) {
+ zval* array = (zval*)closure;
+ TSRMLS_FETCH();
+ RepeatedField* intern =
+ (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+
+ const submsg_handlerdata_t *submsgdata = hd;
+ zval* subdesc_php = get_def_obj((void*)submsgdata->md);
+ Descriptor* subdesc = zend_object_store_get_object(subdesc_php TSRMLS_CC);
+ zend_class_entry* subklass = subdesc->klass;
+ MessageHeader* submsg;
+
+ zval* val = NULL;
+ MAKE_STD_ZVAL(val);
+ Z_TYPE_P(val) = IS_OBJECT;
+ Z_OBJVAL_P(val) = subklass->create_object(subklass TSRMLS_CC);
+
+ repeated_field_push_native(intern, &val TSRMLS_CC);
+
+ submsg = zend_object_store_get_object(val TSRMLS_CC);
+ return submsg;
+}
+
+// Sets a non-repeated submessage field in a message.
+static void *submsg_handler(void *closure, const void *hd) {
+ MessageHeader* msg = closure;
+ const submsg_handlerdata_t* submsgdata = hd;
+ zval* subdesc_php = get_def_obj((void*)submsgdata->md);
+ TSRMLS_FETCH();
+ Descriptor* subdesc = zend_object_store_get_object(subdesc_php TSRMLS_CC);
+ zend_class_entry* subklass = subdesc->klass;
+ zval* submsg_php;
+ MessageHeader* submsg;
+
+ if (Z_TYPE_P(*DEREF(msg, submsgdata->ofs, zval**)) == IS_NULL) {
+ zval* val = NULL;
+ MAKE_STD_ZVAL(val);
+ Z_TYPE_P(val) = IS_OBJECT;
+ Z_OBJVAL_P(val) = subklass->create_object(subklass TSRMLS_CC);
+
+ zval_ptr_dtor(DEREF(msg, submsgdata->ofs, zval**));
+ *DEREF(msg, submsgdata->ofs, zval**) = val;
+ }
+
+ submsg_php = *DEREF(msg, submsgdata->ofs, zval**);
+
+ submsg = zend_object_store_get_object(submsg_php TSRMLS_CC);
+ return submsg;
+}
+
+// Handler data for startmap/endmap handlers.
+typedef struct {
+ size_t ofs;
+ upb_fieldtype_t key_field_type;
+ upb_fieldtype_t value_field_type;
+
+ // We know that we can hold this reference because the handlerdata has the
+ // same lifetime as the upb_handlers struct, and the upb_handlers struct holds
+ // a reference to the upb_msgdef, which in turn has references to its subdefs.
+ const upb_def* value_field_subdef;
+} map_handlerdata_t;
+
+// Temporary frame for map parsing: at the beginning of a map entry message, a
+// submsg handler allocates a frame to hold (i) a reference to the Map object
+// into which this message will be inserted and (ii) storage slots to
+// temporarily hold the key and value for this map entry until the end of the
+// submessage. When the submessage ends, another handler is called to insert the
+// value into the map.
+typedef struct {
+ zval* map;
+ char key_storage[NATIVE_SLOT_MAX_SIZE];
+ char value_storage[NATIVE_SLOT_MAX_SIZE];
+} map_parse_frame_t;
+
+static void map_slot_init(void* memory, upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ // Store zval** in memory in order to be consistent with the layout of
+ // singular fields.
+ zval** holder = ALLOC(zval*);
+ zval* tmp;
+ MAKE_STD_ZVAL(tmp);
+ ZVAL_STRINGL(tmp, "", 0, 1);
+ *holder = tmp;
+ *(zval***)memory = holder;
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ zval** holder = ALLOC(zval*);
+ zval* tmp;
+ MAKE_STD_ZVAL(tmp);
+ ZVAL_NULL(tmp);
+ *holder = tmp;
+ *(zval***)memory = holder;
+ break;
+ }
+ default:
+ native_slot_init(type, memory, NULL);
+ }
+}
+
+static void map_slot_uninit(void* memory, upb_fieldtype_t type) {
+ switch (type) {
+ case UPB_TYPE_MESSAGE:
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ zval** holder = *(zval***)memory;
+ zval_ptr_dtor(holder);
+ FREE(holder);
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+static void map_slot_key(upb_fieldtype_t type, const void* from,
+ const char** keyval,
+ size_t* length) {
+ if (type == UPB_TYPE_STRING) {
+ zval* key_php = **(zval***)from;
+ *keyval = Z_STRVAL_P(key_php);
+ *length = Z_STRLEN_P(key_php);
+ } else {
+ *keyval = from;
+ *length = native_slot_size(type);
+ }
+}
+
+static void map_slot_value(upb_fieldtype_t type, const void* from,
+ upb_value* v) {
+ size_t len;
+ void* to = upb_value_memory(v);
+#ifndef NDEBUG
+ v->ctype = UPB_CTYPE_UINT64;
+#endif
+
+ memset(to, 0, native_slot_size(type));
+
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE: {
+ *(zval**)to = **(zval***)from;
+ Z_ADDREF_PP((zval**)to);
+ break;
+ }
+ default:
+ len = native_slot_size(type);
+ memcpy(to, from, len);
+ }
+}
+
+// Handler to begin a map entry: allocates a temporary frame. This is the
+// 'startsubmsg' handler on the msgdef that contains the map field.
+static void *startmapentry_handler(void *closure, const void *hd) {
+ MessageHeader* msg = closure;
+ const map_handlerdata_t* mapdata = hd;
+ zval* map = *DEREF(msg, mapdata->ofs, zval**);
+
+ map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
+ frame->map = map;
+
+ map_slot_init(&frame->key_storage, mapdata->key_field_type);
+ map_slot_init(&frame->value_storage, mapdata->value_field_type);
+
+ return frame;
+}
+
+// Handler to end a map entry: inserts the value defined during the message into
+// the map. This is the 'endmsg' handler on the map entry msgdef.
+static bool endmap_handler(void* closure, const void* hd, upb_status* s) {
+ map_parse_frame_t* frame = closure;
+ const map_handlerdata_t* mapdata = hd;
+
+ TSRMLS_FETCH();
+ Map *map = (Map *)zend_object_store_get_object(frame->map TSRMLS_CC);
+
+ const char* keyval = NULL;
+ upb_value v;
+ size_t length;
+
+ map_slot_key(map->key_type, &frame->key_storage, &keyval, &length);
+ map_slot_value(map->value_type, &frame->value_storage, &v);
+
+ map_index_set(map, keyval, length, v);
+
+ map_slot_uninit(&frame->key_storage, mapdata->key_field_type);
+ map_slot_uninit(&frame->value_storage, mapdata->value_field_type);
+ FREE(frame);
+
+ return true;
+}
+
+// Allocates a new map_handlerdata_t given the map entry message definition. If
+// the offset of the field within the parent message is also given, that is
+// added to the handler data as well. Note that this is called *twice* per map
+// field: once in the parent message handler setup when setting the startsubmsg
+// handler and once in the map entry message handler setup when setting the
+// key/value and endmsg handlers. The reason is that there is no easy way to
+// pass the handlerdata down to the sub-message handler setup.
+static map_handlerdata_t* new_map_handlerdata(
+ size_t ofs,
+ const upb_msgdef* mapentry_def,
+ Descriptor* desc) {
+ const upb_fielddef* key_field;
+ const upb_fielddef* value_field;
+ // TODO(teboring): Use emalloc and efree.
+ map_handlerdata_t* hd =
+ (map_handlerdata_t*)malloc(sizeof(map_handlerdata_t));
+
+ hd->ofs = ofs;
+ key_field = upb_msgdef_itof(mapentry_def, MAP_KEY_FIELD);
+ assert(key_field != NULL);
+ hd->key_field_type = upb_fielddef_type(key_field);
+ value_field = upb_msgdef_itof(mapentry_def, MAP_VALUE_FIELD);
+ assert(value_field != NULL);
+ hd->value_field_type = upb_fielddef_type(value_field);
+ hd->value_field_subdef = upb_fielddef_subdef(value_field);
+
+ return hd;
+}
+
+// Handlers that set primitive values in oneofs.
+#define DEFINE_ONEOF_HANDLER(type, ctype) \
+ static bool oneof##type##_handler(void *closure, const void *hd, \
+ ctype val) { \
+ const oneof_handlerdata_t *oneofdata = hd; \
+ DEREF(closure, oneofdata->case_ofs, uint32_t) = \
+ oneofdata->oneof_case_num; \
+ DEREF(closure, oneofdata->ofs, ctype) = val; \
+ return true; \
+ }
+
+DEFINE_ONEOF_HANDLER(bool, bool)
+DEFINE_ONEOF_HANDLER(int32, int32_t)
+DEFINE_ONEOF_HANDLER(uint32, uint32_t)
+DEFINE_ONEOF_HANDLER(float, float)
+DEFINE_ONEOF_HANDLER(int64, int64_t)
+DEFINE_ONEOF_HANDLER(uint64, uint64_t)
+DEFINE_ONEOF_HANDLER(double, double)
+
+#undef DEFINE_ONEOF_HANDLER
+
+// Handlers for strings in a oneof.
+static void *oneofstr_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
+ MessageHeader* msg = closure;
+ const oneof_handlerdata_t *oneofdata = hd;
+
+ DEREF(msg, oneofdata->case_ofs, uint32_t) =
+ oneofdata->oneof_case_num;
+ DEREF(msg, oneofdata->ofs, zval**) =
+ &(msg->std.properties_table)[oneofdata->property_ofs];
+
+ return empty_php_string(DEREF(msg, oneofdata->ofs, zval**));
+}
+
+static void *oneofbytes_handler(void *closure,
+ const void *hd,
+ size_t size_hint) {
+ MessageHeader* msg = closure;
+ const oneof_handlerdata_t *oneofdata = hd;
+
+ DEREF(msg, oneofdata->case_ofs, uint32_t) =
+ oneofdata->oneof_case_num;
+ DEREF(msg, oneofdata->ofs, zval**) =
+ &(msg->std.properties_table)[oneofdata->property_ofs];
+
+ // TODO(teboring): Add it back.
+ // rb_enc_associate(str, kRubyString8bitEncoding);
+
+ SEPARATE_ZVAL_IF_NOT_REF(DEREF(msg, oneofdata->ofs, zval**));
+ zval* str = *DEREF(msg, oneofdata->ofs, zval**);
+ zval_dtor(str);
+ ZVAL_STRINGL(str, "", 0, 1);
+ return (void*)str;
+}
+
+// Handler for a submessage field in a oneof.
+static void* oneofsubmsg_handler(void* closure, const void* hd) {
+ MessageHeader* msg = closure;
+ const oneof_handlerdata_t *oneofdata = hd;
+ uint32_t oldcase = DEREF(msg, oneofdata->case_ofs, uint32_t);
+ zval* subdesc_php = get_def_obj((void*)oneofdata->md);
+ TSRMLS_FETCH();
+ Descriptor* subdesc = zend_object_store_get_object(subdesc_php TSRMLS_CC);
+ zend_class_entry* subklass = subdesc->klass;
+ zval* submsg_php;
+ MessageHeader* submsg;
+
+ if (oldcase != oneofdata->oneof_case_num) {
+ DEREF(msg, oneofdata->ofs, zval**) =
+ &(msg->std.properties_table)[oneofdata->property_ofs];
+ }
+
+ if (Z_TYPE_P(*DEREF(msg, oneofdata->ofs, zval**)) == IS_NULL) {
+ zval* val = NULL;
+ MAKE_STD_ZVAL(val);
+ Z_TYPE_P(val) = IS_OBJECT;
+ Z_OBJVAL_P(val) = subklass->create_object(subklass TSRMLS_CC);
+
+ zval_ptr_dtor(DEREF(msg, oneofdata->ofs, zval**));
+ *DEREF(msg, oneofdata->ofs, zval**) = val;
+ }
+
+ DEREF(msg, oneofdata->case_ofs, uint32_t) =
+ oneofdata->oneof_case_num;
+
+ submsg_php = *DEREF(msg, oneofdata->ofs, zval**);
+ submsg = zend_object_store_get_object(submsg_php TSRMLS_CC);
+ return submsg;
+}
+
+// Set up handlers for a repeated field.
+static void add_handlers_for_repeated_field(upb_handlers *h,
+ const upb_fielddef *f,
+ size_t offset) {
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
+ upb_handlers_setstartseq(h, f, startseq_handler, &attr);
+ upb_handlerattr_uninit(&attr);
+
+ switch (upb_fielddef_type(f)) {
+
+#define SET_HANDLER(utype, ltype) \
+ case utype: \
+ upb_handlers_set##ltype(h, f, append##ltype##_handler, NULL); \
+ break;
+
+ SET_HANDLER(UPB_TYPE_BOOL, bool);
+ SET_HANDLER(UPB_TYPE_INT32, int32);
+ SET_HANDLER(UPB_TYPE_UINT32, uint32);
+ SET_HANDLER(UPB_TYPE_ENUM, int32);
+ SET_HANDLER(UPB_TYPE_FLOAT, float);
+ SET_HANDLER(UPB_TYPE_INT64, int64);
+ SET_HANDLER(UPB_TYPE_UINT64, uint64);
+ SET_HANDLER(UPB_TYPE_DOUBLE, double);
+
+#undef SET_HANDLER
+
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
+ upb_handlers_setstartstr(h, f, is_bytes ?
+ appendbytes_handler : appendstr_handler,
+ NULL);
+ upb_handlers_setstring(h, f, stringdata_handler, NULL);
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, 0, f));
+ upb_handlers_setstartsubmsg(h, f, appendsubmsg_handler, &attr);
+ upb_handlerattr_uninit(&attr);
+ break;
+ }
+ }
+}
+
+// Set up handlers for a singular field.
+static void add_handlers_for_singular_field(upb_handlers *h,
+ const upb_fielddef *f,
+ size_t offset) {
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_BOOL:
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_ENUM:
+ case UPB_TYPE_FLOAT:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT64:
+ case UPB_TYPE_DOUBLE:
+ upb_shim_set(h, f, offset, -1);
+ break;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, newhandlerdata(h, offset));
+ upb_handlers_setstartstr(h, f,
+ is_bytes ? bytes_handler : str_handler,
+ &attr);
+ upb_handlers_setstring(h, f, stringdata_handler, &attr);
+ upb_handlerattr_uninit(&attr);
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(&attr, newsubmsghandlerdata(h, offset, f));
+ upb_handlers_setstartsubmsg(h, f, submsg_handler, &attr);
+ upb_handlerattr_uninit(&attr);
+ break;
+ }
+ }
+}
+
+// Adds handlers to a map field.
+static void add_handlers_for_mapfield(upb_handlers* h,
+ const upb_fielddef* fielddef,
+ size_t offset,
+ Descriptor* desc) {
+ const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef);
+ map_handlerdata_t* hd = new_map_handlerdata(offset, map_msgdef, desc);
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+
+ upb_handlers_addcleanup(h, hd, free);
+ upb_handlerattr_sethandlerdata(&attr, hd);
+ upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr);
+ upb_handlerattr_uninit(&attr);
+}
+
+// Adds handlers to a map-entry msgdef.
+static void add_handlers_for_mapentry(const upb_msgdef* msgdef, upb_handlers* h,
+ Descriptor* desc) {
+ const upb_fielddef* key_field = map_entry_key(msgdef);
+ const upb_fielddef* value_field = map_entry_value(msgdef);
+ map_handlerdata_t* hd = new_map_handlerdata(0, msgdef, desc);
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+
+ upb_handlers_addcleanup(h, hd, free);
+ upb_handlerattr_sethandlerdata(&attr, hd);
+ upb_handlers_setendmsg(h, endmap_handler, &attr);
+
+ add_handlers_for_singular_field(h, key_field,
+ offsetof(map_parse_frame_t, key_storage));
+ add_handlers_for_singular_field(h, value_field,
+ offsetof(map_parse_frame_t, value_storage));
+}
+
+// Set up handlers for a oneof field.
+static void add_handlers_for_oneof_field(upb_handlers *h,
+ const upb_fielddef *f,
+ size_t offset,
+ size_t oneof_case_offset,
+ int property_cache_offset) {
+
+ upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
+ upb_handlerattr_sethandlerdata(
+ &attr, newoneofhandlerdata(h, offset, oneof_case_offset,
+ property_cache_offset, f));
+
+ switch (upb_fielddef_type(f)) {
+
+#define SET_HANDLER(utype, ltype) \
+ case utype: \
+ upb_handlers_set##ltype(h, f, oneof##ltype##_handler, &attr); \
+ break;
+
+ SET_HANDLER(UPB_TYPE_BOOL, bool);
+ SET_HANDLER(UPB_TYPE_INT32, int32);
+ SET_HANDLER(UPB_TYPE_UINT32, uint32);
+ SET_HANDLER(UPB_TYPE_ENUM, int32);
+ SET_HANDLER(UPB_TYPE_FLOAT, float);
+ SET_HANDLER(UPB_TYPE_INT64, int64);
+ SET_HANDLER(UPB_TYPE_UINT64, uint64);
+ SET_HANDLER(UPB_TYPE_DOUBLE, double);
+
+#undef SET_HANDLER
+
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ bool is_bytes = upb_fielddef_type(f) == UPB_TYPE_BYTES;
+ upb_handlers_setstartstr(h, f, is_bytes ?
+ oneofbytes_handler : oneofstr_handler,
+ &attr);
+ upb_handlers_setstring(h, f, stringdata_handler, NULL);
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ upb_handlers_setstartsubmsg(h, f, oneofsubmsg_handler, &attr);
+ break;
+ }
+ }
+
+ upb_handlerattr_uninit(&attr);
+}
+
+static void add_handlers_for_message(const void* closure,
+ upb_handlers* h) {
+ const upb_msgdef* msgdef = upb_handlers_msgdef(h);
+ TSRMLS_FETCH();
+ Descriptor* desc = (Descriptor*)zend_object_store_get_object(
+ get_def_obj((void*)msgdef) TSRMLS_CC);
+ upb_msg_field_iter i;
+
+ // If this is a mapentry message type, set up a special set of handlers and
+ // bail out of the normal (user-defined) message type handling.
+ if (upb_msgdef_mapentry(msgdef)) {
+ add_handlers_for_mapentry(msgdef, h, desc);
+ return;
+ }
+
+ // Ensure layout exists. We may be invoked to create handlers for a given
+ // message if we are included as a submsg of another message type before our
+ // class is actually built, so to work around this, we just create the layout
+ // (and handlers, in the class-building function) on-demand.
+ if (desc->layout == NULL) {
+ desc->layout = create_layout(desc->msgdef);
+ }
+
+ for (upb_msg_field_begin(&i, desc->msgdef);
+ !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ const upb_fielddef *f = upb_msg_iter_field(&i);
+ size_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
+ sizeof(MessageHeader);
+
+ if (upb_fielddef_containingoneof(f)) {
+ size_t oneof_case_offset =
+ desc->layout->fields[upb_fielddef_index(f)].case_offset +
+ sizeof(MessageHeader);
+ int property_cache_index =
+ desc->layout->fields[upb_fielddef_index(f)].cache_index;
+ add_handlers_for_oneof_field(h, f, offset, oneof_case_offset,
+ property_cache_index);
+ } else if (is_map_field(f)) {
+ add_handlers_for_mapfield(h, f, offset, desc);
+ } else if (upb_fielddef_isseq(f)) {
+ add_handlers_for_repeated_field(h, f, offset);
+ } else {
+ add_handlers_for_singular_field(h, f, offset);
+ }
+ }
+}
+
+// Creates upb handlers for populating a message.
+static const upb_handlers *new_fill_handlers(Descriptor* desc,
+ const void* owner) {
+ // TODO(cfallin, haberman): once upb gets a caching/memoization layer for
+ // handlers, reuse subdef handlers so that e.g. if we already parse
+ // B-with-field-of-type-C, we don't have to rebuild the whole hierarchy to
+ // parse A-with-field-of-type-B-with-field-of-type-C.
+ return upb_handlers_newfrozen(desc->msgdef, owner,
+ add_handlers_for_message, NULL);
+}
+
+// Constructs the handlers for filling a message's data into an in-memory
+// object.
+const upb_handlers* get_fill_handlers(Descriptor* desc) {
+ if (!desc->fill_handlers) {
+ desc->fill_handlers =
+ new_fill_handlers(desc, &desc->fill_handlers);
+ }
+ return desc->fill_handlers;
+}
+
+const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor* desc,
+ const void* owner) {
+ const upb_handlers* handlers = get_fill_handlers(desc);
+ upb_pbdecodermethodopts opts;
+ upb_pbdecodermethodopts_init(&opts, handlers);
+
+ return upb_pbdecodermethod_new(&opts, owner);
+}
+
+static const upb_pbdecodermethod *msgdef_decodermethod(Descriptor* desc) {
+ if (desc->fill_method == NULL) {
+ desc->fill_method = new_fillmsg_decodermethod(
+ desc, &desc->fill_method);
+ }
+ return desc->fill_method;
+}
+
+// -----------------------------------------------------------------------------
+// Serializing.
+// -----------------------------------------------------------------------------
+
+static void putmsg(zval* msg, const Descriptor* desc, upb_sink* sink,
+ int depth TSRMLS_DC);
+
+static void putstr(zval* str, const upb_fielddef* f, upb_sink* sink);
+
+static void putrawstr(const char* str, int len, const upb_fielddef* f,
+ upb_sink* sink);
+
+static void putsubmsg(zval* submsg, const upb_fielddef* f, upb_sink* sink,
+ int depth TSRMLS_DC);
+
+static void putarray(zval* array, const upb_fielddef* f, upb_sink* sink,
+ int depth TSRMLS_DC);
+static void putmap(zval* map, const upb_fielddef* f, upb_sink* sink, int depth
+ TSRMLS_DC);
+
+static upb_selector_t getsel(const upb_fielddef* f, upb_handlertype_t type) {
+ upb_selector_t ret;
+ bool ok = upb_handlers_getselector(f, type, &ret);
+ UPB_ASSERT(ok);
+ return ret;
+}
+
+static void put_optional_value(const void* memory, int len, const upb_fielddef* f,
+ int depth, upb_sink* sink TSRMLS_DC) {
+ assert(upb_fielddef_label(f) == UPB_LABEL_OPTIONAL);
+
+ switch (upb_fielddef_type(f)) {
+#define T(upbtypeconst, upbtype, ctype, default_value) \
+ case upbtypeconst: { \
+ ctype value = DEREF(memory, 0, ctype); \
+ if (value != default_value) { \
+ upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f)); \
+ upb_sink_put##upbtype(sink, sel, value); \
+ } \
+ } break;
+
+ T(UPB_TYPE_FLOAT, float, float, 0.0)
+ T(UPB_TYPE_DOUBLE, double, double, 0.0)
+ T(UPB_TYPE_BOOL, bool, uint8_t, 0)
+ T(UPB_TYPE_ENUM, int32, int32_t, 0)
+ T(UPB_TYPE_INT32, int32, int32_t, 0)
+ T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
+ T(UPB_TYPE_INT64, int64, int64_t, 0)
+ T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
+
+#undef T
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ putrawstr(memory, len, f, sink);
+ break;
+ case UPB_TYPE_MESSAGE: {
+ zval* submsg = *(zval**)memory;
+ putsubmsg(submsg, f, sink, depth TSRMLS_CC);
+ break;
+ }
+ default:
+ assert(false);
+ }
+}
+
+// Only string/bytes fields are stored as zval.
+static const char* raw_value(void* memory, const upb_fielddef* f) {
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ return Z_STRVAL_PP((zval**)memory);
+ break;
+ default:
+ return memory;
+ }
+}
+
+static int raw_value_len(void* memory, int len, const upb_fielddef* f) {
+ switch (upb_fielddef_type(f)) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ return Z_STRLEN_PP((zval**)memory);
+ break;
+ default:
+ return len;
+ }
+}
+
+static void putmap(zval* map, const upb_fielddef* f, upb_sink* sink,
+ int depth TSRMLS_DC) {
+ Map* self;
+ upb_sink subsink;
+ const upb_fielddef* key_field;
+ const upb_fielddef* value_field;
+ MapIter it;
+ int len;
+
+ if (map == NULL) return;
+ self = UNBOX(Map, map);
+
+ upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
+
+ assert(upb_fielddef_type(f) == UPB_TYPE_MESSAGE);
+ key_field = map_field_key(f);
+ value_field = map_field_value(f);
+
+ for (map_begin(map, &it TSRMLS_CC); !map_done(&it); map_next(&it)) {
+ upb_status status;
+
+ upb_sink entry_sink;
+ upb_sink_startsubmsg(&subsink, getsel(f, UPB_HANDLER_STARTSUBMSG),
+ &entry_sink);
+ upb_sink_startmsg(&entry_sink);
+
+ // Serialize key.
+ const char *key = map_iter_key(&it, &len);
+ put_optional_value(key, len, key_field, depth + 1, &entry_sink TSRMLS_CC);
+
+ // Serialize value.
+ upb_value value = map_iter_value(&it, &len);
+ put_optional_value(raw_value(upb_value_memory(&value), value_field),
+ raw_value_len(upb_value_memory(&value), len, value_field),
+ value_field, depth + 1, &entry_sink TSRMLS_CC);
+
+ upb_sink_endmsg(&entry_sink, &status);
+ upb_sink_endsubmsg(&subsink, getsel(f, UPB_HANDLER_ENDSUBMSG));
+ }
+
+ upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
+}
+
+static void putmsg(zval* msg_php, const Descriptor* desc, upb_sink* sink,
+ int depth TSRMLS_DC) {
+ upb_msg_field_iter i;
+ upb_status status;
+
+ upb_sink_startmsg(sink);
+
+ // Protect against cycles (possible because users may freely reassign message
+ // and repeated fields) by imposing a maximum recursion depth.
+ if (depth > ENCODE_MAX_NESTING) {
+ zend_error(E_ERROR,
+ "Maximum recursion depth exceeded during encoding.");
+ }
+
+ MessageHeader* msg = zend_object_store_get_object(msg_php TSRMLS_CC);
+
+ for (upb_msg_field_begin(&i, desc->msgdef); !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ upb_fielddef* f = upb_msg_iter_field(&i);
+ uint32_t offset = desc->layout->fields[upb_fielddef_index(f)].offset +
+ sizeof(MessageHeader);
+
+ if (upb_fielddef_containingoneof(f)) {
+ uint32_t oneof_case_offset =
+ desc->layout->fields[upb_fielddef_index(f)].case_offset +
+ sizeof(MessageHeader);
+ // For a oneof, check that this field is actually present -- skip all the
+ // below if not.
+ if (DEREF(msg, oneof_case_offset, uint32_t) != upb_fielddef_number(f)) {
+ continue;
+ }
+ // Otherwise, fall through to the appropriate singular-field handler
+ // below.
+ }
+
+ if (is_map_field(f)) {
+ zval* map = *DEREF(msg, offset, zval**);
+ if (map != NULL) {
+ putmap(map, f, sink, depth TSRMLS_CC);
+ }
+ } else if (upb_fielddef_isseq(f)) {
+ zval* array = *DEREF(msg, offset, zval**);
+ if (array != NULL) {
+ putarray(array, f, sink, depth TSRMLS_CC);
+ }
+ } else if (upb_fielddef_isstring(f)) {
+ zval* str = *DEREF(msg, offset, zval**);
+ if (Z_STRLEN_P(str) > 0) {
+ putstr(str, f, sink);
+ }
+ } else if (upb_fielddef_issubmsg(f)) {
+ putsubmsg(*DEREF(msg, offset, zval**), f, sink, depth TSRMLS_CC);
+ } else {
+ upb_selector_t sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
+
+#define T(upbtypeconst, upbtype, ctype, default_value) \
+ case upbtypeconst: { \
+ ctype value = DEREF(msg, offset, ctype); \
+ if (value != default_value) { \
+ upb_sink_put##upbtype(sink, sel, value); \
+ } \
+ } break;
+
+ switch (upb_fielddef_type(f)) {
+ T(UPB_TYPE_FLOAT, float, float, 0.0)
+ T(UPB_TYPE_DOUBLE, double, double, 0.0)
+ T(UPB_TYPE_BOOL, bool, uint8_t, 0)
+ case UPB_TYPE_ENUM:
+ T(UPB_TYPE_INT32, int32, int32_t, 0)
+ T(UPB_TYPE_UINT32, uint32, uint32_t, 0)
+ T(UPB_TYPE_INT64, int64, int64_t, 0)
+ T(UPB_TYPE_UINT64, uint64, uint64_t, 0)
+
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ zend_error(E_ERROR, "Internal error.");
+ }
+
+#undef T
+ }
+ }
+
+ upb_sink_endmsg(sink, &status);
+}
+
+static void putstr(zval* str, const upb_fielddef *f, upb_sink *sink) {
+ upb_sink subsink;
+
+ if (ZVAL_IS_NULL(str)) return;
+
+ assert(Z_TYPE_P(str) == IS_STRING);
+
+ // Ensure that the string has the correct encoding. We also check at field-set
+ // time, but the user may have mutated the string object since then.
+ if (upb_fielddef_type(f) == UPB_TYPE_STRING &&
+ !is_structurally_valid_utf8(Z_STRVAL_P(str), Z_STRLEN_P(str))) {
+ zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
+ return;
+ }
+
+ upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), Z_STRLEN_P(str),
+ &subsink);
+ upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), Z_STRVAL_P(str),
+ Z_STRLEN_P(str), NULL);
+ upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
+}
+
+static void putrawstr(const char* str, int len, const upb_fielddef* f,
+ upb_sink* sink) {
+ upb_sink subsink;
+
+ if (len == 0) return;
+
+ // Ensure that the string has the correct encoding. We also check at field-set
+ // time, but the user may have mutated the string object since then.
+ if (upb_fielddef_type(f) == UPB_TYPE_STRING &&
+ !is_structurally_valid_utf8(str, len)) {
+ zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
+ return;
+ }
+
+ upb_sink_startstr(sink, getsel(f, UPB_HANDLER_STARTSTR), len, &subsink);
+ upb_sink_putstring(&subsink, getsel(f, UPB_HANDLER_STRING), str, len, NULL);
+ upb_sink_endstr(sink, getsel(f, UPB_HANDLER_ENDSTR));
+}
+
+static void putsubmsg(zval* submsg, const upb_fielddef* f, upb_sink* sink,
+ int depth TSRMLS_DC) {
+ upb_sink subsink;
+
+ if (Z_TYPE_P(submsg) == IS_NULL) return;
+
+ zval* php_descriptor = get_def_obj(upb_fielddef_msgsubdef(f));
+ Descriptor* subdesc =
+ (Descriptor*)zend_object_store_get_object(php_descriptor TSRMLS_CC);
+
+ upb_sink_startsubmsg(sink, getsel(f, UPB_HANDLER_STARTSUBMSG), &subsink);
+ putmsg(submsg, subdesc, &subsink, depth + 1 TSRMLS_CC);
+ upb_sink_endsubmsg(sink, getsel(f, UPB_HANDLER_ENDSUBMSG));
+}
+
+static void putarray(zval* array, const upb_fielddef* f, upb_sink* sink,
+ int depth TSRMLS_DC) {
+ upb_sink subsink;
+ upb_fieldtype_t type = upb_fielddef_type(f);
+ upb_selector_t sel = 0;
+ int size, i;
+
+ assert(array != NULL);
+ RepeatedField* intern =
+ (RepeatedField*)zend_object_store_get_object(array TSRMLS_CC);
+ size = zend_hash_num_elements(HASH_OF(intern->array));
+ if (size == 0) return;
+
+ upb_sink_startseq(sink, getsel(f, UPB_HANDLER_STARTSEQ), &subsink);
+
+ if (upb_fielddef_isprimitive(f)) {
+ sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
+ }
+
+ for (i = 0; i < size; i++) {
+ void* memory = repeated_field_index_native(intern, i TSRMLS_CC);
+ switch (type) {
+#define T(upbtypeconst, upbtype, ctype) \
+ case upbtypeconst: \
+ upb_sink_put##upbtype(&subsink, sel, *((ctype*)memory)); \
+ break;
+
+ T(UPB_TYPE_FLOAT, float, float)
+ T(UPB_TYPE_DOUBLE, double, double)
+ T(UPB_TYPE_BOOL, bool, int8_t)
+ case UPB_TYPE_ENUM:
+ T(UPB_TYPE_INT32, int32, int32_t)
+ T(UPB_TYPE_UINT32, uint32, uint32_t)
+ T(UPB_TYPE_INT64, int64, int64_t)
+ T(UPB_TYPE_UINT64, uint64, uint64_t)
+
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ putstr(*((zval**)memory), f, &subsink);
+ break;
+ case UPB_TYPE_MESSAGE:
+ putsubmsg(*((zval**)memory), f, &subsink, depth TSRMLS_CC);
+ break;
+
+#undef T
+ }
+ }
+ upb_sink_endseq(sink, getsel(f, UPB_HANDLER_ENDSEQ));
+}
+
+static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
+ if (desc->pb_serialize_handlers == NULL) {
+ desc->pb_serialize_handlers =
+ upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
+ }
+ return desc->pb_serialize_handlers;
+}
+
+// -----------------------------------------------------------------------------
+// PHP encode/decode methods
+// -----------------------------------------------------------------------------
+
+PHP_METHOD(Message, encode) {
+ zval* php_descriptor = get_ce_obj(Z_OBJCE_P(getThis()));
+ Descriptor* desc =
+ (Descriptor*)zend_object_store_get_object(php_descriptor TSRMLS_CC);
+
+ stringsink sink;
+ stringsink_init(&sink);
+
+ {
+ const upb_handlers* serialize_handlers = msgdef_pb_serialize_handlers(desc);
+
+ stackenv se;
+ upb_pb_encoder* encoder;
+
+ stackenv_init(&se, "Error occurred during encoding: %s");
+ encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
+
+ putmsg(getThis(), desc, upb_pb_encoder_input(encoder), 0 TSRMLS_CC);
+
+ RETVAL_STRINGL(sink.ptr, sink.len, 1);
+
+ stackenv_uninit(&se);
+ stringsink_uninit(&sink);
+ }
+}
+
+PHP_METHOD(Message, decode) {
+ zval* php_descriptor = get_ce_obj(Z_OBJCE_P(getThis()));
+ Descriptor* desc =
+ (Descriptor*)zend_object_store_get_object(php_descriptor TSRMLS_CC);
+ MessageHeader* msg = zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ char *data = NULL;
+ int data_len;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &data, &data_len) ==
+ FAILURE) {
+ return;
+ }
+
+ {
+ const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
+ const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
+ stackenv se;
+ upb_sink sink;
+ upb_pbdecoder* decoder;
+ stackenv_init(&se, "Error occurred during parsing: %s");
+
+ upb_sink_reset(&sink, h, msg);
+ decoder = upb_pbdecoder_create(&se.env, method, &sink);
+ upb_bufsrc_putbuf(data, data_len, upb_pbdecoder_input(decoder));
+
+ stackenv_uninit(&se);
+ }
+}
diff --git a/php/ext/google/protobuf/map.c b/php/ext/google/protobuf/map.c
new file mode 100644
index 00000000..35747b05
--- /dev/null
+++ b/php/ext/google/protobuf/map.c
@@ -0,0 +1,472 @@
+// 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 <ext/spl/spl_iterators.h>
+#include <Zend/zend_API.h>
+#include <Zend/zend_interfaces.h>
+
+#include "protobuf.h"
+#include "utf8.h"
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
+ ZEND_ARG_INFO(0, index)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetSet, 0, 0, 2)
+ ZEND_ARG_INFO(0, index)
+ ZEND_ARG_INFO(0, newval)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO(arginfo_void, 0)
+ZEND_END_ARG_INFO()
+
+// Utilities
+
+void* upb_value_memory(upb_value* v) {
+ return (void*)(&v->val);
+}
+
+// -----------------------------------------------------------------------------
+// Basic map operations on top of upb's strtable.
+//
+// Note that we roll our own `Map` container here because, as for
+// `RepeatedField`, we want a strongly-typed container. This is so that any user
+// errors due to incorrect map key or value types are raised as close as
+// possible to the error site, rather than at some deferred point (e.g.,
+// serialization).
+//
+// We build our `Map` on top of upb_strtable so that we're able to take
+// advantage of the native_slot storage abstraction, as RepeatedField does.
+// (This is not quite a perfect mapping -- see the key conversions below -- but
+// gives us full support and error-checking for all value types for free.)
+// -----------------------------------------------------------------------------
+
+// Map values are stored using the native_slot abstraction (as with repeated
+// field values), but keys are a bit special. Since we use a strtable, we need
+// to store keys as sequences of bytes such that equality of those bytes maps
+// one-to-one to equality of keys. We store strings directly (i.e., they map to
+// their own bytes) and integers as native integers (using the native_slot
+// abstraction).
+
+// Note that there is another tradeoff here in keeping string keys as native
+// strings rather than PHP strings: traversing the Map requires conversion to
+// PHP string values on every traversal, potentially creating more garbage. We
+// should consider ways to cache a PHP version of the key if this becomes an
+// issue later.
+
+// Forms a key to use with the underlying strtable from a PHP key value. |buf|
+// must point to TABLE_KEY_BUF_LENGTH bytes of temporary space, used to
+// construct a key byte sequence if needed. |out_key| and |out_length| provide
+// the resulting key data/length.
+#define TABLE_KEY_BUF_LENGTH 8 // sizeof(uint64_t)
+static bool table_key(Map* self, zval* key,
+ char* buf,
+ const char** out_key,
+ size_t* out_length TSRMLS_DC) {
+ switch (self->key_type) {
+ case UPB_TYPE_STRING:
+ if (!protobuf_convert_to_string(key)) {
+ return false;
+ }
+ if (!is_structurally_valid_utf8(Z_STRVAL_P(key), Z_STRLEN_P(key))) {
+ zend_error(E_USER_ERROR, "Given key is not UTF8 encoded.");
+ return false;
+ }
+ *out_key = Z_STRVAL_P(key);
+ *out_length = Z_STRLEN_P(key);
+ break;
+
+#define CASE_TYPE(upb_type, type, c_type, php_type) \
+ case UPB_TYPE_##upb_type: { \
+ c_type type##_value; \
+ if (!protobuf_convert_to_##type(key, &type##_value)) { \
+ return false; \
+ } \
+ native_slot_set(self->key_type, NULL, buf, key TSRMLS_CC); \
+ *out_key = buf; \
+ *out_length = native_slot_size(self->key_type); \
+ break; \
+ }
+ CASE_TYPE(BOOL, bool, int8_t, BOOL)
+ CASE_TYPE(INT32, int32, int32_t, LONG)
+ CASE_TYPE(INT64, int64, int64_t, LONG)
+ CASE_TYPE(UINT32, uint32, uint32_t, LONG)
+ CASE_TYPE(UINT64, uint64, uint64_t, LONG)
+
+#undef CASE_TYPE
+
+ default:
+ // Map constructor should not allow a Map with another key type to be
+ // constructed.
+ assert(false);
+ break;
+ }
+
+ return true;
+}
+
+// -----------------------------------------------------------------------------
+// MapField methods
+// -----------------------------------------------------------------------------
+
+static zend_function_entry map_field_methods[] = {
+ PHP_ME(MapField, __construct, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(MapField, offsetExists, arginfo_offsetGet, ZEND_ACC_PUBLIC)
+ PHP_ME(MapField, offsetGet, arginfo_offsetGet, ZEND_ACC_PUBLIC)
+ PHP_ME(MapField, offsetSet, arginfo_offsetSet, ZEND_ACC_PUBLIC)
+ PHP_ME(MapField, offsetUnset, arginfo_offsetGet, ZEND_ACC_PUBLIC)
+ PHP_ME(MapField, count, arginfo_void, ZEND_ACC_PUBLIC)
+ ZEND_FE_END
+};
+
+// -----------------------------------------------------------------------------
+// MapField creation/desctruction
+// -----------------------------------------------------------------------------
+
+zend_class_entry* map_field_type;
+zend_object_handlers* map_field_handlers;
+
+static void map_begin_internal(Map *map, MapIter *iter) {
+ iter->self = map;
+ upb_strtable_begin(&iter->it, &map->table);
+}
+
+static HashTable *map_field_get_gc(zval *object, zval ***table,
+ int *n TSRMLS_DC) {
+ // TODO(teboring): Unfortunately, zend engine does not support garbage
+ // collection for custom array. We have to use zend engine's native array
+ // instead.
+ *table = NULL;
+ *n = 0;
+ return NULL;
+}
+
+void map_field_init(TSRMLS_D) {
+ zend_class_entry class_type;
+ const char* class_name = "Google\\Protobuf\\Internal\\MapField";
+ INIT_CLASS_ENTRY_EX(class_type, class_name, strlen(class_name),
+ map_field_methods);
+
+ map_field_type = zend_register_internal_class(&class_type TSRMLS_CC);
+ map_field_type->create_object = map_field_create;
+
+ zend_class_implements(map_field_type TSRMLS_CC, 2, spl_ce_ArrayAccess,
+ spl_ce_Countable);
+
+ map_field_handlers = PEMALLOC(zend_object_handlers);
+ memcpy(map_field_handlers, zend_get_std_object_handlers(),
+ sizeof(zend_object_handlers));
+ map_field_handlers->get_gc = map_field_get_gc;
+}
+
+zend_object_value map_field_create(zend_class_entry *ce TSRMLS_DC) {
+ zend_object_value retval = {0};
+ Map *intern;
+
+ intern = emalloc(sizeof(Map));
+ memset(intern, 0, sizeof(Map));
+
+ zend_object_std_init(&intern->std, ce TSRMLS_CC);
+ object_properties_init(&intern->std, ce);
+
+ // Table value type is always UINT64: this ensures enough space to store the
+ // native_slot value.
+ if (!upb_strtable_init(&intern->table, UPB_CTYPE_UINT64)) {
+ zend_error(E_USER_ERROR, "Could not allocate table.");
+ }
+
+ retval.handle = zend_objects_store_put(
+ intern, (zend_objects_store_dtor_t)zend_objects_destroy_object,
+ (zend_objects_free_object_storage_t)map_field_free, NULL TSRMLS_CC);
+ retval.handlers = map_field_handlers;
+
+ return retval;
+}
+
+void map_field_free(void *object TSRMLS_DC) {
+ Map *map = (Map *)object;
+
+ switch (map->value_type) {
+ case UPB_TYPE_MESSAGE:
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ MapIter it;
+ int len;
+ for (map_begin_internal(map, &it); !map_done(&it); map_next(&it)) {
+ upb_value value = map_iter_value(&it, &len);
+ void *mem = upb_value_memory(&value);
+ zval_ptr_dtor(mem);
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
+ upb_strtable_uninit(&map->table);
+ zend_object_std_dtor(&map->std TSRMLS_CC);
+ efree(object);
+}
+
+void map_field_create_with_type(zend_class_entry *ce, const upb_fielddef *field,
+ zval **map_field TSRMLS_DC) {
+ MAKE_STD_ZVAL(*map_field);
+ Z_TYPE_PP(map_field) = IS_OBJECT;
+ Z_OBJVAL_PP(map_field) =
+ map_field_type->create_object(map_field_type TSRMLS_CC);
+
+ Map* intern =
+ (Map*)zend_object_store_get_object(*map_field TSRMLS_CC);
+
+ const upb_fielddef *key_field = map_field_key(field);
+ const upb_fielddef *value_field = map_field_value(field);
+ intern->key_type = upb_fielddef_type(key_field);
+ intern->value_type = upb_fielddef_type(value_field);
+ intern->msg_ce = field_type_class(value_field TSRMLS_CC);
+}
+
+static void map_field_free_element(void *object) {
+}
+
+// -----------------------------------------------------------------------------
+// MapField Handlers
+// -----------------------------------------------------------------------------
+
+static bool map_field_read_dimension(zval *object, zval *key, int type,
+ zval **retval TSRMLS_DC) {
+ Map *intern =
+ (Map *)zend_object_store_get_object(object TSRMLS_CC);
+
+ char keybuf[TABLE_KEY_BUF_LENGTH];
+ const char* keyval = NULL;
+ size_t length = 0;
+ upb_value v;
+#ifndef NDEBUG
+ v.ctype = UPB_CTYPE_UINT64;
+#endif
+ if (!table_key(intern, key, keybuf, &keyval, &length TSRMLS_CC)) {
+ return false;
+ }
+
+ if (upb_strtable_lookup2(&intern->table, keyval, length, &v)) {
+ void* mem = upb_value_memory(&v);
+ native_slot_get(intern->value_type, mem, retval TSRMLS_CC);
+ return true;
+ } else {
+ zend_error(E_USER_ERROR, "Given key doesn't exist.");
+ return false;
+ }
+}
+
+bool map_index_set(Map *intern, const char* keyval, int length, upb_value v) {
+ // Replace any existing value by issuing a 'remove' operation first.
+ upb_strtable_remove2(&intern->table, keyval, length, NULL);
+ if (!upb_strtable_insert2(&intern->table, keyval, length, v)) {
+ zend_error(E_USER_ERROR, "Could not insert into table");
+ return false;
+ }
+ return true;
+}
+
+static bool map_field_write_dimension(zval *object, zval *key,
+ zval *value TSRMLS_DC) {
+ Map *intern = (Map *)zend_object_store_get_object(object TSRMLS_CC);
+
+ char keybuf[TABLE_KEY_BUF_LENGTH];
+ const char* keyval = NULL;
+ size_t length = 0;
+ upb_value v;
+ void* mem;
+ if (!table_key(intern, key, keybuf, &keyval, &length TSRMLS_CC)) {
+ return false;
+ }
+
+ mem = upb_value_memory(&v);
+ memset(mem, 0, native_slot_size(intern->value_type));
+ if (!native_slot_set(intern->value_type, intern->msg_ce, mem, value
+ TSRMLS_CC)) {
+ return false;
+ }
+#ifndef NDEBUG
+ v.ctype = UPB_CTYPE_UINT64;
+#endif
+
+ // Replace any existing value by issuing a 'remove' operation first.
+ upb_strtable_remove2(&intern->table, keyval, length, NULL);
+ if (!upb_strtable_insert2(&intern->table, keyval, length, v)) {
+ zend_error(E_USER_ERROR, "Could not insert into table");
+ return false;
+ }
+
+ return true;
+}
+
+static bool map_field_unset_dimension(zval *object, zval *key TSRMLS_DC) {
+ Map *intern = (Map *)zend_object_store_get_object(object TSRMLS_CC);
+
+ char keybuf[TABLE_KEY_BUF_LENGTH];
+ const char* keyval = NULL;
+ size_t length = 0;
+ upb_value v;
+ if (!table_key(intern, key, keybuf, &keyval, &length TSRMLS_CC)) {
+ return false;
+ }
+#ifndef NDEBUG
+ v.ctype = UPB_CTYPE_UINT64;
+#endif
+
+ upb_strtable_remove2(&intern->table, keyval, length, &v);
+
+ return true;
+}
+
+// -----------------------------------------------------------------------------
+// PHP MapField Methods
+// -----------------------------------------------------------------------------
+
+PHP_METHOD(MapField, __construct) {
+ long key_type, value_type;
+ zend_class_entry* klass = NULL;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ll|C", &key_type,
+ &value_type, &klass) == FAILURE) {
+ return;
+ }
+
+ Map* intern =
+ (Map*)zend_object_store_get_object(getThis() TSRMLS_CC);
+ intern->key_type = to_fieldtype(key_type);
+ intern->value_type = to_fieldtype(value_type);
+ intern->msg_ce = klass;
+
+ // Check that the key type is an allowed type.
+ switch (intern->key_type) {
+ case UPB_TYPE_INT32:
+ case UPB_TYPE_INT64:
+ case UPB_TYPE_UINT32:
+ case UPB_TYPE_UINT64:
+ case UPB_TYPE_BOOL:
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ // These are OK.
+ break;
+ default:
+ zend_error(E_USER_ERROR, "Invalid key type for map.");
+ }
+}
+
+PHP_METHOD(MapField, offsetExists) {
+ zval *key;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &key) ==
+ FAILURE) {
+ return;
+ }
+
+ Map *intern = (Map *)zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ char keybuf[TABLE_KEY_BUF_LENGTH];
+ const char* keyval = NULL;
+ size_t length = 0;
+ upb_value v;
+#ifndef NDEBUG
+ v.ctype = UPB_CTYPE_UINT64;
+#endif
+ if (!table_key(intern, key, keybuf, &keyval, &length TSRMLS_CC)) {
+ RETURN_BOOL(false);
+ }
+
+ RETURN_BOOL(upb_strtable_lookup2(&intern->table, keyval, length, &v));
+}
+
+PHP_METHOD(MapField, offsetGet) {
+ zval *index, *value;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) ==
+ FAILURE) {
+ return;
+ }
+ map_field_read_dimension(getThis(), index, BP_VAR_R,
+ return_value_ptr TSRMLS_CC);
+}
+
+PHP_METHOD(MapField, offsetSet) {
+ zval *index, *value;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zz", &index, &value) ==
+ FAILURE) {
+ return;
+ }
+ map_field_write_dimension(getThis(), index, value TSRMLS_CC);
+}
+
+PHP_METHOD(MapField, offsetUnset) {
+ zval *index;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &index) ==
+ FAILURE) {
+ return;
+ }
+ map_field_unset_dimension(getThis(), index TSRMLS_CC);
+}
+
+PHP_METHOD(MapField, count) {
+ Map *intern =
+ (Map *)zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ if (zend_parse_parameters_none() == FAILURE) {
+ return;
+ }
+
+ RETURN_LONG(upb_strtable_count(&intern->table));
+}
+
+// -----------------------------------------------------------------------------
+// Map Iterator
+// -----------------------------------------------------------------------------
+
+void map_begin(zval *map_php, MapIter *iter TSRMLS_DC) {
+ Map *self = UNBOX(Map, map_php);
+ map_begin_internal(self, iter);
+}
+
+void map_next(MapIter *iter) {
+ upb_strtable_next(&iter->it);
+}
+
+bool map_done(MapIter *iter) {
+ return upb_strtable_done(&iter->it);
+}
+
+const char *map_iter_key(MapIter *iter, int *len) {
+ *len = upb_strtable_iter_keylength(&iter->it);
+ return upb_strtable_iter_key(&iter->it);
+}
+
+upb_value map_iter_value(MapIter *iter, int *len) {
+ *len = native_slot_size(iter->self->value_type);
+ return upb_strtable_iter_value(&iter->it);
+}
diff --git a/php/ext/google/protobuf/message.c b/php/ext/google/protobuf/message.c
index c062d665..cb46031e 100644
--- a/php/ext/google/protobuf/message.c
+++ b/php/ext/google/protobuf/message.c
@@ -29,245 +29,220 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <php.h>
+#include <stdlib.h>
#include "protobuf.h"
-// -----------------------------------------------------------------------------
-// Class/module creation from msgdefs and enumdefs, respectively.
-// -----------------------------------------------------------------------------
-
-void* message_data(void* msg) {
- return ((uint8_t *)msg) + sizeof(MessageHeader);
-}
-
-void message_set_property(zval* object, zval* field_name, zval* value,
- const zend_literal* key TSRMLS_DC) {
- const upb_fielddef* field;
-
- MessageHeader* self = zend_object_store_get_object(object TSRMLS_CC);
-
- CHECK_TYPE(field_name, IS_STRING);
- field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(field_name));
- if (field == NULL) {
- zend_error(E_ERROR, "Unknown field: %s", Z_STRVAL_P(field_name));
- }
- layout_set(self->descriptor->layout, message_data(self), field, value);
-}
-
-zval* message_get_property(zval* object, zval* member, int type,
- const zend_literal* key TSRMLS_DC) {
- MessageHeader* self =
- (MessageHeader*)zend_object_store_get_object(object TSRMLS_CC);
- CHECK_TYPE(member, IS_STRING);
-
- const upb_fielddef* field;
- field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
- if (field == NULL) {
- return EG(uninitialized_zval_ptr);
- }
- zval* retval = layout_get(self->descriptor->layout, message_data(self), field TSRMLS_CC);
- return retval;
-}
+static zend_class_entry* message_type;
+zend_object_handlers* message_handlers;
static zend_function_entry message_methods[] = {
PHP_ME(Message, encode, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, decode, NULL, ZEND_ACC_PUBLIC)
+ PHP_ME(Message, readOneof, NULL, ZEND_ACC_PROTECTED)
+ PHP_ME(Message, writeOneof, NULL, ZEND_ACC_PROTECTED)
{NULL, NULL, NULL}
};
-/* stringsink *****************************************************************/
+// Forward declare static functions.
-// This should probably be factored into a common upb component.
+static void message_set_property(zval* object, zval* member, zval* value,
+ const zend_literal* key TSRMLS_DC);
+static zval* message_get_property(zval* object, zval* member, int type,
+ const zend_literal* key TSRMLS_DC);
+static zval** message_get_property_ptr_ptr(zval* object, zval* member, int type,
+ const zend_literal* key TSRMLS_DC);
-typedef struct {
- upb_byteshandler handler;
- upb_bytessink sink;
- char *ptr;
- size_t len, size;
-} stringsink;
-
-static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
- stringsink *sink = _sink;
- sink->len = 0;
- return sink;
-}
+static zend_object_value message_create(zend_class_entry* ce TSRMLS_DC);
+static void message_free(void* object TSRMLS_DC);
-static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
- size_t len, const upb_bufhandle *handle) {
- stringsink *sink = _sink;
- size_t new_size = sink->size;
+// -----------------------------------------------------------------------------
+// PHP Message Handlers
+// -----------------------------------------------------------------------------
- UPB_UNUSED(hd);
- UPB_UNUSED(handle);
+void message_init(TSRMLS_D) {
+ zend_class_entry class_type;
+ INIT_CLASS_ENTRY(class_type, "Google\\Protobuf\\Internal\\Message",
+ message_methods);
+ message_type = zend_register_internal_class(&class_type TSRMLS_CC);
+
+ message_handlers = PEMALLOC(zend_object_handlers);
+ memcpy(message_handlers, zend_get_std_object_handlers(),
+ sizeof(zend_object_handlers));
+ message_handlers->write_property = message_set_property;
+ message_handlers->read_property = message_get_property;
+ message_handlers->get_property_ptr_ptr = message_get_property_ptr_ptr;
+}
- while (sink->len + len > new_size) {
- new_size *= 2;
+static void message_set_property(zval* object, zval* member, zval* value,
+ const zend_literal* key TSRMLS_DC) {
+ if (Z_TYPE_P(member) != IS_STRING) {
+ zend_error(E_USER_ERROR, "Unexpected type for field name");
+ return;
}
- if (new_size != sink->size) {
- sink->ptr = realloc(sink->ptr, new_size);
- sink->size = new_size;
+ if (Z_OBJCE_P(object) != EG(scope)) {
+ // User cannot set property directly (e.g., $m->a = 1)
+ zend_error(E_USER_ERROR, "Cannot access private property.");
+ return;
}
- memcpy(sink->ptr + sink->len, ptr, len);
- sink->len += len;
+ const upb_fielddef* field;
+
+ MessageHeader* self = zend_object_store_get_object(object TSRMLS_CC);
+
+ field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
+ if (field == NULL) {
+ zend_error(E_USER_ERROR, "Unknown field: %s", Z_STRVAL_P(member));
+ }
- return len;
+ layout_set(self->descriptor->layout, self, field, value TSRMLS_CC);
}
-void stringsink_init(stringsink *sink) {
- upb_byteshandler_init(&sink->handler);
- upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
- upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
+static zval* message_get_property(zval* object, zval* member, int type,
+ const zend_literal* key TSRMLS_DC) {
+ if (Z_TYPE_P(member) != IS_STRING) {
+ zend_error(E_USER_ERROR, "Property name has to be a string.");
+ return EG(uninitialized_zval_ptr);
+ }
- upb_bytessink_reset(&sink->sink, &sink->handler, sink);
+ if (Z_OBJCE_P(object) != EG(scope)) {
+ // User cannot get property directly (e.g., $a = $m->a)
+ zend_error(E_USER_ERROR, "Cannot access private property.");
+ return EG(uninitialized_zval_ptr);
+ }
- sink->size = 32;
- sink->ptr = malloc(sink->size);
- sink->len = 0;
-}
+ zend_property_info* property_info = NULL;
-void stringsink_uninit(stringsink *sink) { free(sink->ptr); }
-
-// Stack-allocated context during an encode/decode operation. Contains the upb
-// environment and its stack-based allocator, an initial buffer for allocations
-// to avoid malloc() when possible, and a template for PHP exception messages
-// if any error occurs.
-#define STACK_ENV_STACKBYTES 4096
-typedef struct {
- upb_env env;
- upb_seededalloc alloc;
- const char *php_error_template;
- char allocbuf[STACK_ENV_STACKBYTES];
-} stackenv;
-
-static void stackenv_init(stackenv* se, const char* errmsg);
-static void stackenv_uninit(stackenv* se);
-
-// Callback invoked by upb if any error occurs during parsing or serialization.
-static bool env_error_func(void* ud, const upb_status* status) {
- stackenv* se = ud;
- // Free the env -- rb_raise will longjmp up the stack past the encode/decode
- // function so it would not otherwise have been freed.
- stackenv_uninit(se);
-
- // TODO(teboring): have a way to verify that this is actually a parse error,
- // instead of just throwing "parse error" unconditionally.
- zend_error(E_ERROR, se->php_error_template);
- // Never reached.
- return false;
-}
+ // All properties should have been declared in the generated code and have
+ // corresponding zvals in properties_table.
+ ulong h = zend_get_hash_value(Z_STRVAL_P(member), Z_STRLEN_P(member) + 1);
+ if (zend_hash_quick_find(&Z_OBJCE_P(object)->properties_info,
+ Z_STRVAL_P(member), Z_STRLEN_P(member) + 1, h,
+ (void**)&property_info) != SUCCESS) {
+ zend_error(E_USER_ERROR, "Property does not exist.");
+ return EG(uninitialized_zval_ptr);
+ }
+
+ MessageHeader* self =
+ (MessageHeader*)zend_object_store_get_object(object TSRMLS_CC);
-static void stackenv_init(stackenv* se, const char* errmsg) {
- se->php_error_template = errmsg;
- upb_env_init(&se->env);
- upb_seededalloc_init(&se->alloc, &se->allocbuf, STACK_ENV_STACKBYTES);
- upb_env_setallocfunc(&se->env, upb_seededalloc_getallocfunc(&se->alloc),
- &se->alloc);
- upb_env_seterrorfunc(&se->env, env_error_func, se);
+ const upb_fielddef* field;
+ field = upb_msgdef_ntofz(self->descriptor->msgdef, Z_STRVAL_P(member));
+ if (field == NULL) {
+ return EG(uninitialized_zval_ptr);
+ }
+ return layout_get(
+ self->descriptor->layout, message_data(self), field,
+ &Z_OBJ_P(object)->properties_table[property_info->offset] TSRMLS_CC);
}
-static void stackenv_uninit(stackenv* se) {
- upb_env_uninit(&se->env);
- upb_seededalloc_uninit(&se->alloc);
+static zval** message_get_property_ptr_ptr(zval* object, zval* member, int type,
+ const zend_literal* key TSRMLS_DC) {
+ return NULL;
}
// -----------------------------------------------------------------------------
-// Message
+// C Message Utilities
// -----------------------------------------------------------------------------
-static const upb_handlers* msgdef_pb_serialize_handlers(Descriptor* desc) {
- if (desc->pb_serialize_handlers == NULL) {
- desc->pb_serialize_handlers =
- upb_pb_encoder_newhandlers(desc->msgdef, &desc->pb_serialize_handlers);
- }
- return desc->pb_serialize_handlers;
+void* message_data(void* msg) {
+ return ((uint8_t*)msg) + sizeof(MessageHeader);
}
-PHP_METHOD(Message, encode) {
- Descriptor* desc = (Descriptor*)zend_object_store_get_object(
- CE_STATIC_MEMBERS(Z_OBJCE_P(getThis()))[0] TSRMLS_CC);
-
- stringsink sink;
- stringsink_init(&sink);
-
- {
- const upb_handlers* serialize_handlers = msgdef_pb_serialize_handlers(desc);
+static void message_free(void* object TSRMLS_DC) {
+ MessageHeader* msg = (MessageHeader*)object;
+ int i;
- stackenv se;
- upb_pb_encoder* encoder;
-
- stackenv_init(&se, "Error occurred during encoding: %s");
- encoder = upb_pb_encoder_create(&se.env, serialize_handlers, &sink.sink);
-
- putmsg(getThis(), desc, upb_pb_encoder_input(encoder), 0);
-
- RETVAL_STRINGL(sink.ptr, sink.len, 1);
-
- stackenv_uninit(&se);
- stringsink_uninit(&sink);
+ for (i = 0; i < msg->std.ce->default_properties_count; i++) {
+ zval_ptr_dtor(&msg->std.properties_table[i]);
}
+ efree(msg->std.properties_table);
+ efree(msg);
}
-void message_free(void * object TSRMLS_DC) {
- FREE(object);
-}
-
-zend_object_value message_create(zend_class_entry* ce TSRMLS_DC) {
+static zend_object_value message_create(zend_class_entry* ce TSRMLS_DC) {
zend_object_value return_value;
- zval* php_descriptor = get_def_obj(ce);
+ zval* php_descriptor = get_ce_obj(ce);
Descriptor* desc = zend_object_store_get_object(php_descriptor TSRMLS_CC);
MessageHeader* msg = (MessageHeader*)ALLOC_N(
uint8_t, sizeof(MessageHeader) + desc->layout->size);
memset(message_data(msg), 0, desc->layout->size);
- // We wrap first so that everything in the message object is GC-rooted in case
- // a collection happens during object creation in layout_init().
+ // We wrap first so that everything in the message object is GC-rooted in
+ // case a collection happens during object creation in layout_init().
msg->descriptor = desc;
- layout_init(desc->layout, message_data(msg));
zend_object_std_init(&msg->std, ce TSRMLS_CC);
+ object_properties_init(&msg->std, ce);
+ layout_init(desc->layout, message_data(msg), msg->std.properties_table
+ TSRMLS_CC);
return_value.handle = zend_objects_store_put(
- msg, (zend_objects_store_dtor_t)zend_objects_destroy_object,
- message_free, NULL TSRMLS_CC);
+ msg, (zend_objects_store_dtor_t)zend_objects_destroy_object, message_free,
+ NULL TSRMLS_CC);
- return_value.handlers = PROTOBUF_G(message_handlers);
+ return_value.handlers = message_handlers;
return return_value;
}
-const zend_class_entry* build_class_from_descriptor(
- zval* php_descriptor TSRMLS_DC) {
- Descriptor* desc = php_to_descriptor(php_descriptor);
+void build_class_from_descriptor(zval* php_descriptor TSRMLS_DC) {
+ Descriptor* desc = UNBOX(Descriptor, php_descriptor);
+
+ // Map entries don't have existing php class.
+ if (upb_msgdef_mapentry(desc->msgdef)) {
+ return;
+ }
+
+ zend_class_entry* registered_ce = desc->klass;
+
if (desc->layout == NULL) {
MessageLayout* layout = create_layout(desc->msgdef);
desc->layout = layout;
}
- // TODO(teboring): Add it back.
- // if (desc->fill_method == NULL) {
- // desc->fill_method = new_fillmsg_decodermethod(desc, &desc->fill_method);
- // }
-
- const char* name = upb_msgdef_fullname(desc->msgdef);
- if (name == NULL) {
- zend_error(E_ERROR, "Descriptor does not have assigned name.");
+
+ registered_ce->create_object = message_create;
+}
+
+// -----------------------------------------------------------------------------
+// PHP Methods
+// -----------------------------------------------------------------------------
+
+PHP_METHOD(Message, readOneof) {
+ long index;
+
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &index) ==
+ FAILURE) {
+ return;
}
- zend_class_entry class_entry;
- INIT_CLASS_ENTRY_EX(class_entry, name, strlen(name), message_methods);
- zend_class_entry* registered_ce =
- zend_register_internal_class(&class_entry TSRMLS_CC);
+ MessageHeader* msg =
+ (MessageHeader*)zend_object_store_get_object(getThis() TSRMLS_CC);
- add_def_obj(registered_ce, php_descriptor);
+ const upb_fielddef* field = upb_msgdef_itof(msg->descriptor->msgdef, index);
- if (PROTOBUF_G(message_handlers) == NULL) {
- PROTOBUF_G(message_handlers) = ALLOC(zend_object_handlers);
- memcpy(PROTOBUF_G(message_handlers), zend_get_std_object_handlers(),
- sizeof(zend_object_handlers));
- PROTOBUF_G(message_handlers)->write_property = message_set_property;
- PROTOBUF_G(message_handlers)->read_property = message_get_property;
+ int property_cache_index =
+ msg->descriptor->layout->fields[upb_fielddef_index(field)].cache_index;
+ zval** cache_ptr = &(msg->std.properties_table)[property_cache_index];
+
+ layout_get(msg->descriptor->layout, message_data(msg), field,
+ &return_value TSRMLS_CC);
+}
+
+PHP_METHOD(Message, writeOneof) {
+ long index;
+ zval* value;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz", &index, &value) ==
+ FAILURE) {
+ return;
}
- registered_ce->create_object = message_create;
+ MessageHeader* msg =
+ (MessageHeader*)zend_object_store_get_object(getThis() TSRMLS_CC);
+
+ const upb_fielddef* field = upb_msgdef_itof(msg->descriptor->msgdef, index);
+
+ layout_set(msg->descriptor->layout, msg, field, value TSRMLS_CC);
}
diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml
new file mode 100644
index 00000000..01aad411
--- /dev/null
+++ b/php/ext/google/protobuf/package.xml
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<package packagerversion="1.9.5" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd">
+ <name>protobuf</name>
+ <channel>pecl.php.net</channel>
+ <summary>Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data.</summary>
+ <description>https://developers.google.com/protocol-buffers/</description>
+ <lead>
+ <name>Bo Yang</name>
+ <user>stanleycheung</user>
+ <email>protobuf-opensource@google.com</email>
+ <active>yes</active>
+ </lead>
+ <date>2016-09-23</date>
+ <time>16:06:07</time>
+ <version>
+ <release>3.1.0a1</release>
+ <api>3.1.0a1</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <license uri="http://www.opensource.org/licenses/bsd-license.php">New BSD License</license>
+ <notes>
+First alpha release.
+ </notes>
+ <contents>
+ <dir baseinstalldir="/" name="/">
+ <file baseinstalldir="/" name="config.m4" role="src" />
+ <file baseinstalldir="/" name="array.c" role="src" />
+ <file baseinstalldir="/" name="def.c" role="src" />
+ <file baseinstalldir="/" name="encode_decode.c" role="src" />
+ <file baseinstalldir="/" name="map.c" role="src" />
+ <file baseinstalldir="/" name="message.c" role="src" />
+ <file baseinstalldir="/" name="protobuf.c" role="src" />
+ <file baseinstalldir="/" name="protobuf.h" role="src" />
+ <file baseinstalldir="/" name="storage.c" role="src" />
+ <file baseinstalldir="/" name="type_check.c" role="src" />
+ <file baseinstalldir="/" name="upb.c" role="src" />
+ <file baseinstalldir="/" name="upb.h" role="src" />
+ <file baseinstalldir="/" name="utf8.c" role="src" />
+ <file baseinstalldir="/" name="utf8.h" role="src" />
+ </dir>
+ </contents>
+ <dependencies>
+ <required>
+ <php>
+ <min>5.5.9</min>
+ </php>
+ <pearinstaller>
+ <min>1.4.0</min>
+ </pearinstaller>
+ </required>
+ </dependencies>
+ <providesextension>protobuf</providesextension>
+ <extsrcrelease />
+ <changelog>
+ <release>
+ <version>
+ <release>3.1.0a1</release>
+ <api>3.1.0a1</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <date>2016-09-23</date>
+ <time>16:06:07</time>
+ <license uri="http://www.opensource.org/licenses/bsd-license.php">New BSD License</license>
+ <notes>
+First alpha release
+ </notes>
+ </release>
+ </changelog>
+</package>
diff --git a/php/ext/google/protobuf/protobuf.c b/php/ext/google/protobuf/protobuf.c
index b1ace8b0..ea85b999 100644
--- a/php/ext/google/protobuf/protobuf.c
+++ b/php/ext/google/protobuf/protobuf.c
@@ -1,3 +1,33 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
#include "protobuf.h"
#include <zend_hash.h>
@@ -5,56 +35,81 @@
ZEND_DECLARE_MODULE_GLOBALS(protobuf)
static PHP_GINIT_FUNCTION(protobuf);
static PHP_GSHUTDOWN_FUNCTION(protobuf);
+static PHP_RINIT_FUNCTION(protobuf);
+static PHP_RSHUTDOWN_FUNCTION(protobuf);
+static PHP_MINIT_FUNCTION(protobuf);
+static PHP_MSHUTDOWN_FUNCTION(protobuf);
-// -----------------------------------------------------------------------------
// Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
// instances.
+static HashTable* upb_def_to_php_obj_map;
+// Global map from message/enum's php class entry to corresponding wrapper
+// Descriptor/EnumDescriptor instances.
+static HashTable* ce_to_php_obj_map;
+
+// -----------------------------------------------------------------------------
+// Global maps.
// -----------------------------------------------------------------------------
-void add_def_obj(const void* def, zval* value) {
- uint nIndex = (ulong)def & PROTOBUF_G(upb_def_to_php_obj_map).nTableMask;
+static void add_to_table(HashTable* t, const void* def, void* value) {
+ uint nIndex = (ulong)def & t->nTableMask;
zval* pDest = NULL;
- Z_ADDREF_P(value);
- zend_hash_index_update(&PROTOBUF_G(upb_def_to_php_obj_map), (zend_ulong)def,
- &value, sizeof(zval*), &pDest);
+ zend_hash_index_update(t, (zend_ulong)def, &value, sizeof(zval*), (void**)&pDest);
}
-zval* get_def_obj(const void* def) {
- zval** value;
- if (zend_hash_index_find(&PROTOBUF_G(upb_def_to_php_obj_map), (zend_ulong)def,
- &value) == FAILURE) {
+static void* get_from_table(const HashTable* t, const void* def) {
+ void** value;
+ if (zend_hash_index_find(t, (zend_ulong)def, (void**)&value) == FAILURE) {
zend_error(E_ERROR, "PHP object not found for given definition.\n");
return NULL;
}
return *value;
}
+static void add_to_list(HashTable* t, void* value) {
+ zval* pDest = NULL;
+ zend_hash_next_index_insert(t, &value, sizeof(void*), (void**)&pDest);
+}
+
+void add_def_obj(const void* def, zval* value) {
+ Z_ADDREF_P(value);
+ add_to_table(upb_def_to_php_obj_map, def, value);
+}
+
+zval* get_def_obj(const void* def) {
+ return (zval*)get_from_table(upb_def_to_php_obj_map, def);
+}
+
+void add_ce_obj(const void* ce, zval* value) {
+ Z_ADDREF_P(value);
+ add_to_table(ce_to_php_obj_map, ce, value);
+}
+
+zval* get_ce_obj(const void* ce) {
+ return (zval*)get_from_table(ce_to_php_obj_map, ce);
+}
+
// -----------------------------------------------------------------------------
// Utilities.
// -----------------------------------------------------------------------------
-// define the function(s) we want to add
zend_function_entry protobuf_functions[] = {
- ZEND_FE(get_generated_pool, NULL)
ZEND_FE_END
};
-// "protobuf_functions" refers to the struct defined above
-// we'll be filling in more of this later: you can use this to specify
-// globals, php.ini info, startup and teardown functions, etc.
zend_module_entry protobuf_module_entry = {
STANDARD_MODULE_HEADER,
- PHP_PROTOBUF_EXTNAME, // extension name
- protobuf_functions, // function list
- PHP_MINIT(protobuf), // process startup
- NULL, // process shutdown
- NULL, // request startup
- NULL, // request shutdown
- NULL, // extension info
+ PHP_PROTOBUF_EXTNAME, // extension name
+ protobuf_functions, // function list
+ PHP_MINIT(protobuf), // process startup
+ PHP_MSHUTDOWN(protobuf), // process shutdown
+ PHP_RINIT(protobuf), // request shutdown
+ PHP_RSHUTDOWN(protobuf), // request shutdown
+ NULL, // extension info
PHP_PROTOBUF_VERSION, // extension version
PHP_MODULE_GLOBALS(protobuf), // globals descriptor
- PHP_GINIT(protobuf), // globals ctor
+ PHP_GINIT(protobuf), // globals ctor
PHP_GSHUTDOWN(protobuf), // globals dtor
NULL, // post deactivate
STANDARD_MODULE_PROPERTIES_EX
@@ -65,25 +120,57 @@ ZEND_GET_MODULE(protobuf)
// global variables
static PHP_GINIT_FUNCTION(protobuf) {
- protobuf_globals->generated_pool = NULL;
- generated_pool = NULL;
- protobuf_globals->message_handlers = NULL;
- zend_hash_init(&protobuf_globals->upb_def_to_php_obj_map, 16, NULL,
- ZVAL_PTR_DTOR, 0);
}
static PHP_GSHUTDOWN_FUNCTION(protobuf) {
- if (protobuf_globals->generated_pool != NULL) {
- FREE_ZVAL(protobuf_globals->generated_pool);
- }
- if (protobuf_globals->message_handlers != NULL) {
- FREE(protobuf_globals->message_handlers);
+}
+
+static PHP_RINIT_FUNCTION(protobuf) {
+ ALLOC_HASHTABLE(upb_def_to_php_obj_map);
+ zend_hash_init(upb_def_to_php_obj_map, 16, NULL, ZVAL_PTR_DTOR, 0);
+
+ ALLOC_HASHTABLE(ce_to_php_obj_map);
+ zend_hash_init(ce_to_php_obj_map, 16, NULL, ZVAL_PTR_DTOR, 0);
+
+ generated_pool = NULL;
+ generated_pool_php = NULL;
+
+ return 0;
+}
+
+static PHP_RSHUTDOWN_FUNCTION(protobuf) {
+ zend_hash_destroy(upb_def_to_php_obj_map);
+ FREE_HASHTABLE(upb_def_to_php_obj_map);
+
+ zend_hash_destroy(ce_to_php_obj_map);
+ FREE_HASHTABLE(ce_to_php_obj_map);
+
+ if (generated_pool_php != NULL) {
+ zval_dtor(generated_pool_php);
+ FREE_ZVAL(generated_pool_php);
}
- zend_hash_destroy(&protobuf_globals->upb_def_to_php_obj_map);
+
+ return 0;
}
-PHP_MINIT_FUNCTION(protobuf) {
+static PHP_MINIT_FUNCTION(protobuf) {
+ map_field_init(TSRMLS_C);
+ repeated_field_init(TSRMLS_C);
+ repeated_field_iter_init(TSRMLS_C);
+ gpb_type_init(TSRMLS_C);
+ message_init(TSRMLS_C);
descriptor_pool_init(TSRMLS_C);
descriptor_init(TSRMLS_C);
- message_builder_context_init(TSRMLS_C);
+ enum_descriptor_init(TSRMLS_C);
+ util_init(TSRMLS_C);
+
+ return 0;
+}
+
+static PHP_MSHUTDOWN_FUNCTION(protobuf) {
+ PEFREE(message_handlers);
+ PEFREE(repeated_field_handlers);
+ PEFREE(map_field_handlers);
+
+ return 0;
}
diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h
index f9038550..fb5879dc 100644
--- a/php/ext/google/protobuf/protobuf.h
+++ b/php/ext/google/protobuf/protobuf.h
@@ -1,64 +1,106 @@
+// 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_PHP_PROTOBUF_H__
#define __GOOGLE_PROTOBUF_PHP_PROTOBUF_H__
#include <php.h>
+// ubp.h has to be placed after php.h. Othwise, php.h will introduce NDEBUG.
#include "upb.h"
#define PHP_PROTOBUF_EXTNAME "protobuf"
-#define PHP_PROTOBUF_VERSION "0.01"
+#define PHP_PROTOBUF_VERSION "3.1.0a1"
+
+#define MAX_LENGTH_OF_INT64 20
+#define SIZEOF_INT64 8
+
+// -----------------------------------------------------------------------------
+// Forward Declaration
+// ----------------------------------------------------------------------------
-// Forward decls.
struct DescriptorPool;
struct Descriptor;
-struct FieldDescriptor;
struct EnumDescriptor;
-struct MessageLayout;
+struct FieldDescriptor;
struct MessageField;
struct MessageHeader;
-struct MessageBuilderContext;
-struct EnumBuilderContext;
+struct MessageLayout;
+struct RepeatedField;
+struct RepeatedFieldIter;
+struct MapField;
typedef struct DescriptorPool DescriptorPool;
typedef struct Descriptor Descriptor;
-typedef struct FieldDescriptor FieldDescriptor;
-typedef struct OneofDescriptor OneofDescriptor;
typedef struct EnumDescriptor EnumDescriptor;
-typedef struct MessageLayout MessageLayout;
+typedef struct FieldDescriptor FieldDescriptor;
typedef struct MessageField MessageField;
typedef struct MessageHeader MessageHeader;
-typedef struct MessageBuilderContext MessageBuilderContext;
-typedef struct OneofBuilderContext OneofBuilderContext;
-typedef struct EnumBuilderContext EnumBuilderContext;
-
-extern zend_class_entry* builder_type;
-extern zend_class_entry* descriptor_type;
-extern zend_class_entry* message_builder_context_type;
+typedef struct MessageLayout MessageLayout;
+typedef struct RepeatedField RepeatedField;
+typedef struct RepeatedFieldIter RepeatedFieldIter;
+typedef struct MapField MapField;
-extern DescriptorPool* generated_pool; // The actual generated pool
+// -----------------------------------------------------------------------------
+// Globals.
+// -----------------------------------------------------------------------------
ZEND_BEGIN_MODULE_GLOBALS(protobuf)
- zval* generated_pool;
- zend_object_handlers* message_handlers;
- HashTable upb_def_to_php_obj_map;
ZEND_END_MODULE_GLOBALS(protobuf)
-ZEND_DECLARE_MODULE_GLOBALS(protobuf)
+// Init module and PHP classes.
+void descriptor_init(TSRMLS_D);
+void enum_descriptor_init(TSRMLS_D);
+void descriptor_pool_init(TSRMLS_D);
+void gpb_type_init(TSRMLS_D);
+void map_field_init(TSRMLS_D);
+void repeated_field_init(TSRMLS_D);
+void repeated_field_iter_init(TSRMLS_D);
+void util_init(TSRMLS_D);
+void message_init(TSRMLS_D);
-#ifdef ZTS
-#define PROTOBUF_G(v) TSRMG(protobuf_globals_id, zend_protobuf_globals*, v)
-#else
-#define PROTOBUF_G(v) (protobuf_globals.v)
-#endif
+// Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
+// instances.
+void add_def_obj(const void* def, zval* value);
+zval* get_def_obj(const void* def);
-// -----------------------------------------------------------------------------
-// PHP functions and global variables.
-// -----------------------------------------------------------------------------
+// Global map from PHP class entries to wrapper Descriptor/EnumDescriptor
+// instances.
+void add_ce_obj(const void* ce, zval* value);
+zval* get_ce_obj(const void* ce);
-PHP_MINIT_FUNCTION(protobuf);
+extern zend_class_entry* map_field_type;
+extern zend_class_entry* repeated_field_type;
// -----------------------------------------------------------------------------
-// PHP class structure.
+// Descriptor.
// -----------------------------------------------------------------------------
struct DescriptorPool {
@@ -67,72 +109,112 @@ struct DescriptorPool {
HashTable* pending_list;
};
+PHP_METHOD(DescriptorPool, getGeneratedPool);
+PHP_METHOD(DescriptorPool, internalAddGeneratedFile);
+
+extern zval* generated_pool_php; // wrapper of generated pool
+extern DescriptorPool* generated_pool; // The actual generated pool
+
struct Descriptor {
zend_object std;
const upb_msgdef* msgdef;
MessageLayout* layout;
- // zval* klass; // begins as NULL
- // const upb_handlers* fill_handlers;
- // const upb_pbdecodermethod* fill_method;
+ zend_class_entry* klass; // begins as NULL
+ const upb_handlers* fill_handlers;
+ const upb_pbdecodermethod* fill_method;
const upb_handlers* pb_serialize_handlers;
- // const upb_handlers* json_serialize_handlers;
- // Handlers hold type class references for sub-message fields directly in some
- // cases. We need to keep these rooted because they might otherwise be
- // collected.
- // zval_array typeclass_references;
};
+extern zend_class_entry* descriptor_type;
+
+void descriptor_name_set(Descriptor *desc, const char *name);
+
struct FieldDescriptor {
zend_object std;
const upb_fielddef* fielddef;
};
-struct OneofDescriptor {
- zend_object std;
- const upb_oneofdef* oneofdef;
-};
-
struct EnumDescriptor {
zend_object std;
const upb_enumdef* enumdef;
- // zval* module; // begins as NULL
+ zend_class_entry* klass; // begins as NULL
+ // VALUE module; // begins as nil
};
+extern zend_class_entry* enum_descriptor_type;
+
// -----------------------------------------------------------------------------
-// Native slot storage abstraction.
+// Message class creation.
// -----------------------------------------------------------------------------
-#define NATIVE_SLOT_MAX_SIZE sizeof(uint64_t)
-
-size_t native_slot_size(upb_fieldtype_t type);
+void* message_data(void* msg);
-#define MAP_KEY_FIELD 1
-#define MAP_VALUE_FIELD 2
+// Build PHP class for given descriptor. Instead of building from scratch, this
+// function modifies existing class which has been partially defined in PHP
+// code.
+void build_class_from_descriptor(zval* php_descriptor TSRMLS_DC);
-// Oneof case slot value to indicate that no oneof case is set. The value `0` is
-// safe because field numbers are used as case identifiers, and no field can
-// have a number of 0.
-#define ONEOF_CASE_NONE 0
-
-// These operate on a map field (i.e., a repeated field of submessages whose
-// submessage type is a map-entry msgdef).
-bool is_map_field(const upb_fielddef* field);
-const upb_fielddef* map_field_key(const upb_fielddef* field);
-const upb_fielddef* map_field_value(const upb_fielddef* field);
-
-// These operate on a map-entry msgdef.
-const upb_fielddef* map_entry_key(const upb_msgdef* msgdef);
-const upb_fielddef* map_entry_value(const upb_msgdef* msgdef);
+extern zend_object_handlers* message_handlers;
// -----------------------------------------------------------------------------
// Message layout / storage.
// -----------------------------------------------------------------------------
+/*
+ * In c extension, each protobuf message is a zval instance. The zval instance
+ * is like union, which can be used to store int, string, zend_object_value and
+ * etc. For protobuf message, the zval instance is used to store the
+ * zend_object_value.
+ *
+ * The zend_object_value is composed of handlers and a handle to look up the
+ * actual stored data. The handlers are pointers to functions, e.g., read,
+ * write, and etc, to access properties.
+ *
+ * The actual data of protobuf messages is stored as MessageHeader in zend
+ * engine's central repository. Each MessageHeader instance is composed of a
+ * zend_object, a Descriptor instance and the real message data.
+ *
+ * For the reason that PHP's native types may not be large enough to store
+ * protobuf message's field (e.g., int64), all message's data is stored in
+ * custom memory layout and is indexed by the Descriptor instance.
+ *
+ * The zend_object contains the zend class entry and the properties table. The
+ * zend class entry contains all information about protobuf message's
+ * corresponding PHP class. The most useful information is the offset table of
+ * properties. Because read access to properties requires returning zval
+ * instance, we need to convert data from the custom layout to zval instance.
+ * Instead of creating zval instance for every read access, we use the zval
+ * instances in the properties table in the zend_object as cache. When
+ * accessing properties, the offset is needed to find the zval property in
+ * zend_object's properties table. These properties will be updated using the
+ * data from custom memory layout only when reading these properties.
+ *
+ * zval
+ * |-zend_object_value obj
+ * |-zend_object_handlers* handlers -> |-read_property_handler
+ * | |-write_property_handler
+ * | ++++++++++++++++++++++
+ * |-zend_object_handle handle -> + central repository +
+ * ++++++++++++++++++++++
+ * MessageHeader <-----------------|
+ * |-zend_object std
+ * | |-class_entry* ce -> class_entry
+ * | | |-HashTable properties_table (name->offset)
+ * | |-zval** properties_table <------------------------------|
+ * | |------> zval* property(cache)
+ * |-Descriptor* desc (name->offset)
+ * |-void** data <-----------|
+ * |-----------------------> void* property(data)
+ *
+ */
+
#define MESSAGE_FIELD_NO_CASE ((size_t)-1)
struct MessageField {
size_t offset;
- size_t case_offset; // for oneofs, a uint32. Else, MESSAGE_FIELD_NO_CASE.
+ int cache_index; // Each field except oneof field has a zval cache to avoid
+ // multiple creation when being accessed.
+ size_t case_offset; // for oneofs, a uint32. Else, MESSAGE_FIELD_NO_CASE.
};
struct MessageLayout {
@@ -141,141 +223,245 @@ struct MessageLayout {
size_t size;
};
-void layout_init(MessageLayout* layout, void* storage);
-zval* layout_get(MessageLayout* layout, const void* storage,
- const upb_fielddef* field TSRMLS_DC);
+struct MessageHeader {
+ zend_object std; // Stores properties table and class info of PHP instance.
+ // This is needed for MessageHeader to be accessed via PHP.
+ Descriptor* descriptor; // Kept alive by self.class.descriptor reference.
+ // The real message data is appended after MessageHeader.
+};
+
MessageLayout* create_layout(const upb_msgdef* msgdef);
+void layout_init(MessageLayout* layout, void* storage, zval** properties_table
+ TSRMLS_DC);
+zval* layout_get(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field, zval** cache TSRMLS_DC);
+void layout_set(MessageLayout* layout, MessageHeader* header,
+ const upb_fielddef* field, zval* val TSRMLS_DC);
void free_layout(MessageLayout* layout);
-zval* native_slot_get(upb_fieldtype_t type, /*VALUE type_class,*/
- const void* memory TSRMLS_DC);
+
+PHP_METHOD(Message, readOneof);
+PHP_METHOD(Message, writeOneof);
// -----------------------------------------------------------------------------
-// Message class creation.
+// Encode / Decode.
// -----------------------------------------------------------------------------
-struct MessageHeader {
- zend_object std;
- Descriptor* descriptor; // kept alive by self.class.descriptor reference.
- // Data comes after this.
-};
+// Maximum depth allowed during encoding, to avoid stack overflows due to
+// cycles.
+#define ENCODE_MAX_NESTING 63
+
+// Constructs the upb decoder method for parsing messages of this type.
+// This is called from the message class creation code.
+const upb_pbdecodermethod *new_fillmsg_decodermethod(Descriptor *desc,
+ const void *owner);
+
+PHP_METHOD(Message, encode);
+PHP_METHOD(Message, decode);
+
+// -----------------------------------------------------------------------------
+// Type check / conversion.
+// -----------------------------------------------------------------------------
+
+bool protobuf_convert_to_int32(zval* from, int32_t* to);
+bool protobuf_convert_to_uint32(zval* from, uint32_t* to);
+bool protobuf_convert_to_int64(zval* from, int64_t* to);
+bool protobuf_convert_to_uint64(zval* from, uint64_t* to);
+bool protobuf_convert_to_float(zval* from, float* to);
+bool protobuf_convert_to_double(zval* from, double* to);
+bool protobuf_convert_to_bool(zval* from, int8_t* to);
+bool protobuf_convert_to_string(zval* from);
+
+PHP_METHOD(Util, checkInt32);
+PHP_METHOD(Util, checkUint32);
+PHP_METHOD(Util, checkInt64);
+PHP_METHOD(Util, checkUint64);
+PHP_METHOD(Util, checkEnum);
+PHP_METHOD(Util, checkFloat);
+PHP_METHOD(Util, checkDouble);
+PHP_METHOD(Util, checkBool);
+PHP_METHOD(Util, checkString);
+PHP_METHOD(Util, checkBytes);
+PHP_METHOD(Util, checkMessage);
+PHP_METHOD(Util, checkRepeatedField);
+
+// -----------------------------------------------------------------------------
+// Native slot storage abstraction.
+// -----------------------------------------------------------------------------
-struct MessageBuilderContext {
+#define NATIVE_SLOT_MAX_SIZE sizeof(uint64_t)
+
+size_t native_slot_size(upb_fieldtype_t type);
+bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
+ void* memory, zval* value TSRMLS_DC);
+void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache);
+// For each property, in order to avoid conversion between the zval object and
+// the actual data type during parsing/serialization, the containing message
+// object use the custom memory layout to store the actual data type for each
+// property inside of it. To access a property from php code, the property
+// needs to be converted to a zval object. The message object is not responsible
+// for providing such a zval object. Instead the caller needs to provide one
+// (cache) and update it with the actual data (memory).
+void native_slot_get(upb_fieldtype_t type, const void* memory,
+ zval** cache TSRMLS_DC);
+void native_slot_get_default(upb_fieldtype_t type, zval** cache TSRMLS_DC);
+
+// -----------------------------------------------------------------------------
+// Map Field.
+// -----------------------------------------------------------------------------
+
+extern zend_object_handlers* map_field_handlers;
+
+typedef struct {
zend_object std;
- zval* descriptor;
- zval* pool;
-};
+ upb_fieldtype_t key_type;
+ upb_fieldtype_t value_type;
+ const zend_class_entry* msg_ce; // class entry for value message
+ upb_strtable table;
+} Map;
+
+typedef struct {
+ Map* self;
+ upb_strtable_iter it;
+} MapIter;
+
+void map_begin(zval* self, MapIter* iter TSRMLS_DC);
+void map_next(MapIter* iter);
+bool map_done(MapIter* iter);
+const char* map_iter_key(MapIter* iter, int* len);
+upb_value map_iter_value(MapIter* iter, int* len);
+
+// These operate on a map-entry msgdef.
+const upb_fielddef* map_entry_key(const upb_msgdef* msgdef);
+const upb_fielddef* map_entry_value(const upb_msgdef* msgdef);
+
+zend_object_value map_field_create(zend_class_entry *ce TSRMLS_DC);
+void map_field_create_with_type(zend_class_entry *ce, const upb_fielddef *field,
+ zval **map_field TSRMLS_DC);
+void map_field_free(void* object TSRMLS_DC);
+void* upb_value_memory(upb_value* v);
-struct OneofBuilderContext {
+#define MAP_KEY_FIELD 1
+#define MAP_VALUE_FIELD 2
+
+// These operate on a map field (i.e., a repeated field of submessages whose
+// submessage type is a map-entry msgdef).
+bool is_map_field(const upb_fielddef* field);
+const upb_fielddef* map_field_key(const upb_fielddef* field);
+const upb_fielddef* map_field_value(const upb_fielddef* field);
+
+bool map_index_set(Map *intern, const char* keyval, int length, upb_value v);
+
+PHP_METHOD(MapField, __construct);
+PHP_METHOD(MapField, offsetExists);
+PHP_METHOD(MapField, offsetGet);
+PHP_METHOD(MapField, offsetSet);
+PHP_METHOD(MapField, offsetUnset);
+PHP_METHOD(MapField, count);
+
+// -----------------------------------------------------------------------------
+// Repeated Field.
+// -----------------------------------------------------------------------------
+
+extern zend_object_handlers* repeated_field_handlers;
+
+struct RepeatedField {
zend_object std;
- // VALUE descriptor;
- // VALUE builder;
+ zval* array;
+ upb_fieldtype_t type;
+ const zend_class_entry* msg_ce; // class entry for containing message
+ // (for message field only).
};
-struct EnumBuilderContext {
+struct RepeatedFieldIter {
zend_object std;
- // VALUE enumdesc;
+ RepeatedField* repeated_field;
+ long position;
};
-// Forward-declare all of the PHP method implementations.
-
-DescriptorPool* php_to_descriptor_pool(zval* value TSRMLS_DC);
-zend_object_value descriptor_pool_create(zend_class_entry *ce TSRMLS_DC);
-void descriptor_pool_free_c(DescriptorPool* object TSRMLS_DC);
-void descriptor_pool_free(void* object TSRMLS_DC);
-void descriptor_pool_init_c_instance(DescriptorPool* pool TSRMLS_DC);
-PHP_METHOD(DescriptorPool, addMessage);
-PHP_METHOD(DescriptorPool, finalize);
-
-Descriptor* php_to_descriptor(zval* value TSRMLS_DC);
-zend_object_value descriptor_create(zend_class_entry *ce TSRMLS_DC);
-void descriptor_init_c_instance(Descriptor* intern TSRMLS_DC);
-void descriptor_free_c(Descriptor* object TSRMLS_DC);
-void descriptor_free(void* object TSRMLS_DC);
-void descriptor_name_set(Descriptor *desc, const char *name);
+void repeated_field_create_with_type(zend_class_entry* ce,
+ const upb_fielddef* field,
+ zval** repeated_field TSRMLS_DC);
+// Return the element at the index position from the repeated field. There is
+// not restriction on the type of stored elements.
+void *repeated_field_index_native(RepeatedField *intern, int index TSRMLS_DC);
+// Add the element to the end of the repeated field. There is not restriction on
+// the type of stored elements.
+void repeated_field_push_native(RepeatedField *intern, void *value TSRMLS_DC);
+
+PHP_METHOD(RepeatedField, __construct);
+PHP_METHOD(RepeatedField, append);
+PHP_METHOD(RepeatedField, offsetExists);
+PHP_METHOD(RepeatedField, offsetGet);
+PHP_METHOD(RepeatedField, offsetSet);
+PHP_METHOD(RepeatedField, offsetUnset);
+PHP_METHOD(RepeatedField, count);
+PHP_METHOD(RepeatedField, getIterator);
+
+PHP_METHOD(RepeatedFieldIter, rewind);
+PHP_METHOD(RepeatedFieldIter, current);
+PHP_METHOD(RepeatedFieldIter, key);
+PHP_METHOD(RepeatedFieldIter, next);
+PHP_METHOD(RepeatedFieldIter, valid);
-MessageBuilderContext* php_to_message_builder_context(zval* value TSRMLS_DC);
-zend_object_value message_builder_context_create(
- zend_class_entry* ce TSRMLS_DC);
-void message_builder_context_init_c_instance(
- MessageBuilderContext* intern TSRMLS_DC);
-void message_builder_context_free_c(MessageBuilderContext* object TSRMLS_DC);
-void message_builder_context_free(void* object TSRMLS_DC);
-PHP_METHOD(MessageBuilderContext, optional);
-PHP_METHOD(MessageBuilderContext, finalizeToPool);
+// -----------------------------------------------------------------------------
+// Oneof Field.
+// -----------------------------------------------------------------------------
-PHP_METHOD(Message, encode);
-const zend_class_entry* build_class_from_descriptor(
- zval* php_descriptor TSRMLS_DC);
+typedef struct {
+ zend_object std;
+ upb_oneofdef* oneofdef;
+ int index; // Index of field in oneof. -1 if not set.
+ char value[NATIVE_SLOT_MAX_SIZE];
+} Oneof;
-PHP_FUNCTION(get_generated_pool);
+// Oneof case slot value to indicate that no oneof case is set. The value `0` is
+// safe because field numbers are used as case identifiers, and no field can
+// have a number of 0.
+#define ONEOF_CASE_NONE 0
// -----------------------------------------------------------------------------
-// Global map from upb {msg,enum}defs to wrapper Descriptor/EnumDescriptor
-// instances.
-// ----------------------------------------------------------------------------
+// Upb.
+// -----------------------------------------------------------------------------
-void add_def_obj(const void* def, zval* value);
-zval* get_def_obj(const void* def);
+upb_fieldtype_t to_fieldtype(upb_descriptortype_t type);
+const zend_class_entry *field_type_class(const upb_fielddef *field TSRMLS_DC);
// -----------------------------------------------------------------------------
// Utilities.
// -----------------------------------------------------------------------------
-// PHP Array utils.
-#define Z_ARRVAL_SIZE_P(zval_p) zend_hash_num_elements(Z_ARRVAL_P(zval_p))
-#define Z_ARRVAL_BEGIN_P(zval_p) Z_ARRVAL_P(zval_p)->pListHead
-#define Z_BUCKET_NEXT_PP(bucket_pp) *bucket_pp = (*bucket_pp)->pListNext
-
-#define DEFINE_PHP_OBJECT(class_name, class_name_lower, name) \
- do { \
- zval* name; \
- MAKE_STD_ZVAL(name); \
- object_init_ex(name, class_name_lower##_type); \
- } while (0)
-
-#define DEFINE_PHP_WRAPPER(class_name, class_name_lower, name, intern) \
- zval* name; \
- MAKE_STD_ZVAL(name); \
- object_init_ex(name, class_name_lower##_type); \
- Z_OBJVAL_P(name) \
- .handle = zend_objects_store_put( \
- intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, \
- class_name_lower##_free, NULL TSRMLS_CC);
-
-#define DEFINE_PHP_ZVAL(name) \
- do { \
- zval* name; \
- MAKE_STD_ZVAL(name); \
- } while (0)
-
-#define DEFINE_PHP_STRING(name, value) \
- do { \
- zval* name; \
- MAKE_STD_ZVAL(name); \
- ZVAL_STRING(name, value, 1); \
- } while (0)
-
-// Upb Utilities
-
-void check_upb_status(const upb_status* status, const char* msg);
-
-#define CHECK_UPB(code, msg) \
- do { \
- upb_status status = UPB_STATUS_INIT; \
- code; \
- check_upb_status(&status, msg); \
- } while (0)
+// PHP <-> C conversion.
+#define UNBOX(class_name, val) \
+ (class_name*)zend_object_store_get_object(val TSRMLS_CC);
-// Memory management
+#define BOX(class_name, wrapper, intern, free_func) \
+ MAKE_STD_ZVAL(wrapper); \
+ Z_TYPE_P(wrapper) = IS_OBJECT; \
+ Z_OBJVAL_P(wrapper) \
+ .handle = \
+ zend_objects_store_put(intern, NULL, free_func, NULL TSRMLS_CC); \
+ Z_OBJVAL_P(wrapper).handlers = zend_get_std_object_handlers();
+// Memory management
#define ALLOC(class_name) (class_name*) emalloc(sizeof(class_name))
+#define PEMALLOC(class_name) (class_name*) pemalloc(sizeof(class_name), 1)
#define ALLOC_N(class_name, n) (class_name*) emalloc(sizeof(class_name) * n)
#define FREE(object) efree(object)
-
-// Type Checking
-#define CHECK_TYPE(field, type) \
- if (Z_TYPE_P(field) != type) { \
- zend_error(E_ERROR, "Unexpected type"); \
- }
+#define PEFREE(object) pefree(object, 1)
+
+// Create PHP internal instance.
+#define CREATE(class_name, intern, init_func) \
+ intern = ALLOC(class_name); \
+ memset(intern, 0, sizeof(class_name)); \
+ init_func(intern TSRMLS_CC);
+
+// String argument.
+#define STR(str) (str), strlen(str)
+
+// Zend Value
+#define Z_OBJ_P(zval_p) \
+ ((zend_object*)(EG(objects_store) \
+ .object_buckets[Z_OBJ_HANDLE_P(zval_p)] \
+ .bucket.obj.object))
#endif // __GOOGLE_PROTOBUF_PHP_PROTOBUF_H__
diff --git a/php/ext/google/protobuf/storage.c b/php/ext/google/protobuf/storage.c
index e5a09c17..1d25a91b 100644
--- a/php/ext/google/protobuf/storage.c
+++ b/php/ext/google/protobuf/storage.c
@@ -1,19 +1,43 @@
+// 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 <stdint.h>
#include <protobuf.h>
+#include <Zend/zend.h>
+
+#include "utf8.h"
// -----------------------------------------------------------------------------
-// PHP <-> native slot management.
+// Native slot storage.
// -----------------------------------------------------------------------------
-static zval* int32_to_zval(int32_t value) {
- zval* tmp;
- MAKE_STD_ZVAL(tmp);
- ZVAL_LONG(tmp, value);
- php_printf("int32 to zval\n");
- // ZVAL_LONG(tmp, 1);
- return tmp;
-}
-
#define DEREF(memory, type) *(type*)(memory)
size_t native_slot_size(upb_fieldtype_t type) {
@@ -21,9 +45,9 @@ size_t native_slot_size(upb_fieldtype_t type) {
case UPB_TYPE_FLOAT: return 4;
case UPB_TYPE_DOUBLE: return 8;
case UPB_TYPE_BOOL: return 1;
- case UPB_TYPE_STRING: return sizeof(zval*);
- case UPB_TYPE_BYTES: return sizeof(zval*);
- case UPB_TYPE_MESSAGE: return sizeof(zval*);
+ case UPB_TYPE_STRING: return sizeof(void*);
+ case UPB_TYPE_BYTES: return sizeof(void*);
+ case UPB_TYPE_MESSAGE: return sizeof(void*);
case UPB_TYPE_ENUM: return 4;
case UPB_TYPE_INT32: return 4;
case UPB_TYPE_INT64: return 8;
@@ -33,72 +57,77 @@ size_t native_slot_size(upb_fieldtype_t type) {
}
}
-static bool is_php_num(zval* value) {
- // Is numerial string also valid?
- return (Z_TYPE_P(value) == IS_LONG ||
- Z_TYPE_P(value) == IS_DOUBLE);
-}
+bool native_slot_set(upb_fieldtype_t type, const zend_class_entry* klass,
+ void* memory, zval* value TSRMLS_DC) {
+ switch (type) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ if (!protobuf_convert_to_string(value)) {
+ return false;
+ }
+ if (type == UPB_TYPE_STRING &&
+ !is_structurally_valid_utf8(Z_STRVAL_P(value), Z_STRLEN_P(value))) {
+ zend_error(E_USER_ERROR, "Given string is not UTF8 encoded.");
+ return false;
+ }
+ if (*(zval**)memory != NULL) {
+ REPLACE_ZVAL_VALUE((zval**)memory, value, 1);
+ } else {
+ // Handles repeated/map string field. Memory provided by
+ // RepeatedField/Map is not initialized.
+ MAKE_STD_ZVAL(DEREF(memory, zval*));
+ ZVAL_STRINGL(DEREF(memory, zval*), Z_STRVAL_P(value), Z_STRLEN_P(value),
+ 1);
+ }
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_NULL) {
+ zend_error(E_USER_ERROR, "Given value is not message.");
+ return false;
+ }
+ if (Z_TYPE_P(value) == IS_OBJECT && klass != Z_OBJCE_P(value)) {
+ zend_error(E_USER_ERROR, "Given message does not have correct class.");
+ return false;
+ }
+ if (EXPECTED(DEREF(memory, zval*) != value)) {
+ if (DEREF(memory, zval*) != NULL) {
+ zval_ptr_dtor((zval**)memory);
+ }
+ DEREF(memory, zval*) = value;
+ Z_ADDREF_P(value);
+ }
+ break;
+ }
-void native_slot_check_int_range_precision(upb_fieldtype_t type, zval* val) {
- // TODO(teboring): Add it back.
- // if (!is_php_num(val)) {
- // zend_error(E_ERROR, "Expected number type for integral field.");
- // }
-
- // if (Z_TYPE_P(val) == IS_DOUBLE) {
- // double dbl_val = NUM2DBL(val);
- // if (floor(dbl_val) != dbl_val) {
- // zend_error(E_ERROR,
- // "Non-integral floating point value assigned to integer field.");
- // }
- // }
- // if (type == UPB_TYPE_UINT32 || type == UPB_TYPE_UINT64) {
- // if (NUM2DBL(val) < 0) {
- // zend_error(E_ERROR,
- // "Assigning negative value to unsigned integer field.");
- // }
- // }
-}
+#define CASE_TYPE(upb_type, type, c_type, php_type) \
+ case UPB_TYPE_##upb_type: { \
+ c_type type##_value; \
+ if (protobuf_convert_to_##type(value, &type##_value)) { \
+ DEREF(memory, c_type) = type##_value; \
+ } \
+ break; \
+ }
+ CASE_TYPE(INT32, int32, int32_t, LONG)
+ CASE_TYPE(UINT32, uint32, uint32_t, LONG)
+ CASE_TYPE(ENUM, int32, int32_t, LONG)
+ CASE_TYPE(INT64, int64, int64_t, LONG)
+ CASE_TYPE(UINT64, uint64, uint64_t, LONG)
+ CASE_TYPE(FLOAT, float, float, DOUBLE)
+ CASE_TYPE(DOUBLE, double, double, DOUBLE)
+ CASE_TYPE(BOOL, bool, int8_t, BOOL)
+
+#undef CASE_TYPE
-zval* native_slot_get(upb_fieldtype_t type, /*VALUE type_class,*/
- const void* memory TSRMLS_DC) {
- zval* retval = NULL;
- switch (type) {
- // TODO(teboring): Add it back.
- // case UPB_TYPE_FLOAT:
- // return DBL2NUM(DEREF(memory, float));
- // case UPB_TYPE_DOUBLE:
- // return DBL2NUM(DEREF(memory, double));
- // case UPB_TYPE_BOOL:
- // return DEREF(memory, int8_t) ? Qtrue : Qfalse;
- // case UPB_TYPE_STRING:
- // case UPB_TYPE_BYTES:
- // case UPB_TYPE_MESSAGE:
- // return DEREF(memory, VALUE);
- // case UPB_TYPE_ENUM: {
- // int32_t val = DEREF(memory, int32_t);
- // VALUE symbol = enum_lookup(type_class, INT2NUM(val));
- // if (symbol == Qnil) {
- // return INT2NUM(val);
- // } else {
- // return symbol;
- // }
- // }
- case UPB_TYPE_INT32:
- return int32_to_zval(DEREF(memory, int32_t));
- // TODO(teboring): Add it back.
- // case UPB_TYPE_INT64:
- // return LL2NUM(DEREF(memory, int64_t));
- // case UPB_TYPE_UINT32:
- // return UINT2NUM(DEREF(memory, uint32_t));
- // case UPB_TYPE_UINT64:
- // return ULL2NUM(DEREF(memory, uint64_t));
default:
- return EG(uninitialized_zval_ptr);
+ break;
}
+
+ return true;
}
-void native_slot_init(upb_fieldtype_t type, void* memory) {
+void native_slot_init(upb_fieldtype_t type, void* memory, zval** cache) {
+ zval* tmp = NULL;
switch (type) {
case UPB_TYPE_FLOAT:
DEREF(memory, float) = 0.0;
@@ -109,17 +138,11 @@ void native_slot_init(upb_fieldtype_t type, void* memory) {
case UPB_TYPE_BOOL:
DEREF(memory, int8_t) = 0;
break;
- // TODO(teboring): Add it back.
- // case UPB_TYPE_STRING:
- // case UPB_TYPE_BYTES:
- // DEREF(memory, VALUE) = php_str_new2("");
- // php_enc_associate(DEREF(memory, VALUE), (type == UPB_TYPE_BYTES)
- // ? kRubyString8bitEncoding
- // : kRubyStringUtf8Encoding);
- // break;
- // case UPB_TYPE_MESSAGE:
- // DEREF(memory, VALUE) = Qnil;
- // break;
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ DEREF(memory, zval**) = cache;
+ break;
case UPB_TYPE_ENUM:
case UPB_TYPE_INT32:
DEREF(memory, int32_t) = 0;
@@ -138,122 +161,113 @@ void native_slot_init(upb_fieldtype_t type, void* memory) {
}
}
-void native_slot_set(upb_fieldtype_t type, /*VALUE type_class,*/ void* memory,
- zval* value) {
- native_slot_set_value_and_case(type, /*type_class,*/ memory, value, NULL, 0);
-}
-
-void native_slot_set_value_and_case(upb_fieldtype_t type, /*VALUE type_class,*/
- void* memory, zval* value,
- uint32_t* case_memory,
- uint32_t case_number) {
+void native_slot_get(upb_fieldtype_t type, const void* memory,
+ zval** cache TSRMLS_DC) {
switch (type) {
- case UPB_TYPE_FLOAT:
- if (!Z_TYPE_P(value) == IS_LONG) {
- zend_error(E_ERROR, "Expected number type for float field.");
- }
- DEREF(memory, float) = Z_DVAL_P(value);
- break;
- case UPB_TYPE_DOUBLE:
- // TODO(teboring): Add it back.
- // if (!is_php_num(value)) {
- // zend_error(E_ERROR, "Expected number type for double field.");
- // }
- // DEREF(memory, double) = Z_DVAL_P(value);
- break;
- case UPB_TYPE_BOOL: {
- int8_t val = -1;
- if (zval_is_true(value)) {
- val = 1;
- } else {
- val = 0;
+#define CASE(upb_type, php_type, c_type) \
+ case UPB_TYPE_##upb_type: \
+ SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_##php_type(*cache, DEREF(memory, c_type)); \
+ return;
+
+CASE(FLOAT, DOUBLE, float)
+CASE(DOUBLE, DOUBLE, double)
+CASE(BOOL, BOOL, int8_t)
+CASE(INT32, LONG, int32_t)
+CASE(ENUM, LONG, uint32_t)
+
+#undef CASE
+
+#if SIZEOF_LONG == 4
+#define CASE(upb_type, c_type) \
+ case UPB_TYPE_##upb_type: { \
+ SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ char buffer[MAX_LENGTH_OF_INT64]; \
+ sprintf(buffer, "%lld", DEREF(memory, c_type)); \
+ ZVAL_STRING(*cache, buffer, 1); \
+ return; \
+ }
+#else
+#define CASE(upb_type, c_type) \
+ case UPB_TYPE_##upb_type: { \
+ SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_LONG(*cache, DEREF(memory, c_type)); \
+ return; \
+ }
+#endif
+CASE(UINT64, uint64_t)
+CASE(INT64, int64_t)
+#undef CASE
+
+ case UPB_TYPE_UINT32: {
+ // Prepend bit-1 for negative numbers, so that uint32 value will be
+ // consistent on both 32-bit and 64-bit architectures.
+ SEPARATE_ZVAL_IF_NOT_REF(cache);
+ int value = DEREF(memory, int32_t);
+ if (sizeof(int) == 8) {
+ value |= (-((value >> 31) & 0x1) & 0xFFFFFFFF00000000);
}
- // TODO(teboring): Add it back.
- // else if (value == Qfalse) {
- // val = 0;
- // }
- // else {
- // php_raise(php_eTypeError, "Invalid argument for boolean field.");
- // }
- DEREF(memory, int8_t) = val;
- break;
+ ZVAL_LONG(*cache, value);
+ return;
}
+
case UPB_TYPE_STRING:
case UPB_TYPE_BYTES: {
- // TODO(teboring): Add it back.
- // if (Z_TYPE_P(value) != IS_STRING) {
- // zend_error(E_ERROR, "Invalid argument for string field.");
- // }
- // native_slot_validate_string_encoding(type, value);
- // DEREF(memory, zval*) = value;
+ // For optional string/bytes fields, the cache is owned by the containing
+ // message and should have been updated during setting/decoding. However,
+ // for repeated string/bytes fields, the cache is provided by zend engine
+ // and has not been updated.
+ zval* value = DEREF(memory, zval*);
+ if (*cache != value) {
+ ZVAL_STRINGL(*cache, Z_STRVAL_P(value), Z_STRLEN_P(value), 1);
+ }
break;
}
case UPB_TYPE_MESSAGE: {
- // TODO(teboring): Add it back.
- // if (CLASS_OF(value) == CLASS_OF(Qnil)) {
- // value = Qnil;
- // } else if (CLASS_OF(value) != type_class) {
- // php_raise(php_eTypeError,
- // "Invalid type %s to assign to submessage field.",
- // php_class2name(CLASS_OF(value)));
- // }
- // DEREF(memory, VALUE) = value;
- break;
- }
- case UPB_TYPE_ENUM: {
- // TODO(teboring): Add it back.
- // int32_t int_val = 0;
- // if (!is_php_num(value) && TYPE(value) != T_SYMBOL) {
- // php_raise(php_eTypeError,
- // "Expected number or symbol type for enum field.");
- // }
- // if (TYPE(value) == T_SYMBOL) {
- // // Ensure that the given symbol exists in the enum module.
- // VALUE lookup = php_funcall(type_class, php_intern("resolve"), 1, value);
- // if (lookup == Qnil) {
- // php_raise(php_eRangeError, "Unknown symbol value for enum field.");
- // } else {
- // int_val = NUM2INT(lookup);
- // }
- // } else {
- // native_slot_check_int_range_precision(UPB_TYPE_INT32, value);
- // int_val = NUM2INT(value);
- // }
- // DEREF(memory, int32_t) = int_val;
- // break;
- }
- case UPB_TYPE_INT32:
- case UPB_TYPE_INT64:
- case UPB_TYPE_UINT32:
- case UPB_TYPE_UINT64:
- native_slot_check_int_range_precision(type, value);
- switch (type) {
- case UPB_TYPE_INT32:
- php_printf("Setting INT32 field\n");
- DEREF(memory, int32_t) = Z_LVAL_P(value);
- break;
- case UPB_TYPE_INT64:
- // TODO(teboring): Add it back.
- // DEREF(memory, int64_t) = NUM2LL(value);
- break;
- case UPB_TYPE_UINT32:
- // TODO(teboring): Add it back.
- // DEREF(memory, uint32_t) = NUM2UINT(value);
- break;
- case UPB_TYPE_UINT64:
- // TODO(teboring): Add it back.
- // DEREF(memory, uint64_t) = NUM2ULL(value);
- break;
- default:
- break;
+ // Same as above for string/bytes fields.
+ zval* value = DEREF(memory, zval*);
+ if (*cache != value) {
+ ZVAL_ZVAL(*cache, value, 1, 0);
}
- break;
+ return;
+ }
default:
- break;
+ return;
}
+}
- if (case_memory != NULL) {
- *case_memory = case_number;
+void native_slot_get_default(upb_fieldtype_t type, zval** cache TSRMLS_DC) {
+ switch (type) {
+#define CASE(upb_type, php_type) \
+ case UPB_TYPE_##upb_type: \
+ SEPARATE_ZVAL_IF_NOT_REF(cache); \
+ ZVAL_##php_type(*cache, 0); \
+ return;
+
+ CASE(FLOAT, DOUBLE)
+ CASE(DOUBLE, DOUBLE)
+ CASE(BOOL, BOOL)
+ CASE(INT32, LONG)
+ CASE(INT64, LONG)
+ CASE(UINT32, LONG)
+ CASE(UINT64, LONG)
+ CASE(ENUM, LONG)
+
+#undef CASE
+
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ SEPARATE_ZVAL_IF_NOT_REF(cache);
+ ZVAL_STRINGL(*cache, "", 0, 1);
+ break;
+ }
+ case UPB_TYPE_MESSAGE: {
+ SEPARATE_ZVAL_IF_NOT_REF(cache);
+ ZVAL_NULL(*cache);
+ return;
+ }
+ default:
+ return;
}
}
@@ -281,6 +295,41 @@ bool is_map_field(const upb_fielddef* field) {
return tryget_map_entry_msgdef(field) != NULL;
}
+const upb_fielddef* map_field_key(const upb_fielddef* field) {
+ const upb_msgdef* subdef = map_entry_msgdef(field);
+ return map_entry_key(subdef);
+}
+
+const upb_fielddef* map_field_value(const upb_fielddef* field) {
+ const upb_msgdef* subdef = map_entry_msgdef(field);
+ return map_entry_value(subdef);
+}
+
+const upb_fielddef* map_entry_key(const upb_msgdef* msgdef) {
+ const upb_fielddef* key_field = upb_msgdef_itof(msgdef, MAP_KEY_FIELD);
+ assert(key_field != NULL);
+ return key_field;
+}
+
+const upb_fielddef* map_entry_value(const upb_msgdef* msgdef) {
+ const upb_fielddef* value_field = upb_msgdef_itof(msgdef, MAP_VALUE_FIELD);
+ assert(value_field != NULL);
+ return value_field;
+}
+
+const zend_class_entry* field_type_class(const upb_fielddef* field TSRMLS_DC) {
+ if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
+ zval* desc_php = get_def_obj(upb_fielddef_subdef(field));
+ Descriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ return desc->klass;
+ } else if (upb_fielddef_type(field) == UPB_TYPE_ENUM) {
+ zval* desc_php = get_def_obj(upb_fielddef_subdef(field));
+ EnumDescriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ return desc->klass;
+ }
+ return NULL;
+}
+
// -----------------------------------------------------------------------------
// Memory layout management.
// -----------------------------------------------------------------------------
@@ -290,12 +339,29 @@ static size_t align_up_to(size_t offset, size_t granularity) {
return (offset + granularity - 1) & ~(granularity - 1);
}
+static void* slot_memory(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field) {
+ return ((uint8_t*)storage) + layout->fields[upb_fielddef_index(field)].offset;
+}
+
+static uint32_t* slot_oneof_case(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field) {
+ return (uint32_t*)(((uint8_t*)storage) +
+ layout->fields[upb_fielddef_index(field)].case_offset);
+}
+
+static int slot_property_cache(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field) {
+ return layout->fields[upb_fielddef_index(field)].cache_index;
+}
+
MessageLayout* create_layout(const upb_msgdef* msgdef) {
MessageLayout* layout = ALLOC(MessageLayout);
int nfields = upb_msgdef_numfields(msgdef);
upb_msg_field_iter it;
upb_msg_oneof_iter oit;
size_t off = 0;
+ int i = 0;
layout->fields = ALLOC_N(MessageField, nfields);
@@ -322,6 +388,7 @@ MessageLayout* create_layout(const upb_msgdef* msgdef) {
layout->fields[upb_fielddef_index(field)].offset = off;
layout->fields[upb_fielddef_index(field)].case_offset =
MESSAGE_FIELD_NO_CASE;
+ layout->fields[upb_fielddef_index(field)].cache_index = i++;
off += field_size;
}
@@ -353,11 +420,13 @@ MessageLayout* create_layout(const upb_msgdef* msgdef) {
upb_oneof_next(&fit)) {
const upb_fielddef* field = upb_oneof_iter_field(&fit);
layout->fields[upb_fielddef_index(field)].offset = off;
+ layout->fields[upb_fielddef_index(field)].cache_index = i;
}
+ i++;
off += field_size;
}
- // Now the case fields.
+ // Now the case offset.
for (upb_msg_oneof_begin(&oit, msgdef); !upb_msg_oneof_done(&oit);
upb_msg_oneof_next(&oit)) {
const upb_oneofdef* oneof = upb_msg_iter_oneof(&oit);
@@ -389,151 +458,127 @@ void free_layout(MessageLayout* layout) {
FREE(layout);
}
-// TODO(teboring): Add it back.
-// VALUE field_type_class(const upb_fielddef* field) {
-// VALUE type_class = Qnil;
-// if (upb_fielddef_type(field) == UPB_TYPE_MESSAGE) {
-// VALUE submsgdesc = get_def_obj(upb_fielddef_subdef(field));
-// type_class = Descriptor_msgclass(submsgdesc);
-// } else if (upb_fielddef_type(field) == UPB_TYPE_ENUM) {
-// VALUE subenumdesc = get_def_obj(upb_fielddef_subdef(field));
-// type_class = EnumDescriptor_enummodule(subenumdesc);
-// }
-// return type_class;
-// }
+void layout_init(MessageLayout* layout, void* storage, zval** properties_table
+ TSRMLS_DC) {
+ int i;
+ upb_msg_field_iter it;
+ for (upb_msg_field_begin(&it, layout->msgdef), i = 0; !upb_msg_field_done(&it);
+ upb_msg_field_next(&it), i++) {
+ const upb_fielddef* field = upb_msg_iter_field(&it);
+ void* memory = slot_memory(layout, storage, field);
+ uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
+ int cache_index = slot_property_cache(layout, storage, field);
+ zval** property_ptr = &properties_table[cache_index];
-static void* slot_memory(MessageLayout* layout, const void* storage,
- const upb_fielddef* field) {
- return ((uint8_t*)storage) + layout->fields[upb_fielddef_index(field)].offset;
+ if (upb_fielddef_containingoneof(field)) {
+ memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
+ *oneof_case = ONEOF_CASE_NONE;
+ } else if (is_map_field(field)) {
+ zval_ptr_dtor(property_ptr);
+ map_field_create_with_type(map_field_type, field, property_ptr TSRMLS_CC);
+ DEREF(memory, zval**) = property_ptr;
+ } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
+ zval_ptr_dtor(property_ptr);
+ repeated_field_create_with_type(repeated_field_type, field, property_ptr
+ TSRMLS_CC);
+ DEREF(memory, zval**) = property_ptr;
+ } else {
+ native_slot_init(upb_fielddef_type(field), memory, property_ptr);
+ }
+ }
}
-static uint32_t* slot_oneof_case(MessageLayout* layout, const void* storage,
- const upb_fielddef* field) {
- return (uint32_t*)(((uint8_t*)storage) +
- layout->fields[upb_fielddef_index(field)].case_offset);
+// For non-singular fields, the related memory needs to point to the actual
+// zval in properties table first.
+static void* value_memory(const upb_fielddef* field, void* memory) {
+ switch (upb_fielddef_type(field)) {
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES:
+ case UPB_TYPE_MESSAGE:
+ memory = DEREF(memory, zval**);
+ break;
+ default:
+ // No operation
+ break;
+ }
+ return memory;
}
-void layout_set(MessageLayout* layout, void* storage, const upb_fielddef* field,
- zval* val) {
+zval* layout_get(MessageLayout* layout, const void* storage,
+ const upb_fielddef* field, zval** cache TSRMLS_DC) {
void* memory = slot_memory(layout, storage, field);
uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
if (upb_fielddef_containingoneof(field)) {
- if (Z_TYPE_P(val) == IS_NULL) {
- // Assigning nil to a oneof field clears the oneof completely.
- *oneof_case = ONEOF_CASE_NONE;
- memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
+ if (*oneof_case != upb_fielddef_number(field)) {
+ native_slot_get_default(upb_fielddef_type(field), cache TSRMLS_CC);
} else {
- // The transition between field types for a single oneof (union) slot is
- // somewhat complex because we need to ensure that a GC triggered at any
- // point by a call into the Ruby VM sees a valid state for this field and
- // does not either go off into the weeds (following what it thinks is a
- // VALUE but is actually a different field type) or miss an object (seeing
- // what it thinks is a primitive field but is actually a VALUE for the new
- // field type).
- //
- // In order for the transition to be safe, the oneof case slot must be in
- // sync with the value slot whenever the Ruby VM has been called. Thus, we
- // use native_slot_set_value_and_case(), which ensures that both the value
- // and case number are altered atomically (w.r.t. the Ruby VM).
- native_slot_set_value_and_case(upb_fielddef_type(field),
- /*field_type_class(field),*/ memory, val,
- oneof_case, upb_fielddef_number(field));
+ native_slot_get(upb_fielddef_type(field), value_memory(field, memory),
+ cache TSRMLS_CC);
}
- } else if (is_map_field(field)) {
- // TODO(teboring): Add it back.
- // check_map_field_type(val, field);
- // DEREF(memory, zval*) = val;
+ return *cache;
} else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
- // TODO(teboring): Add it back.
- // check_repeated_field_type(val, field);
- // DEREF(memory, zval*) = val;
+ return *cache;
} else {
- native_slot_set(upb_fielddef_type(field), /*field_type_class(field),*/ memory,
- val);
+ native_slot_get(upb_fielddef_type(field), value_memory(field, memory),
+ cache TSRMLS_CC);
+ return *cache;
}
}
-void layout_init(MessageLayout* layout, void* storage) {
- upb_msg_field_iter it;
- for (upb_msg_field_begin(&it, layout->msgdef); !upb_msg_field_done(&it);
- upb_msg_field_next(&it)) {
- const upb_fielddef* field = upb_msg_iter_field(&it);
- void* memory = slot_memory(layout, storage, field);
- uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
-
- if (upb_fielddef_containingoneof(field)) {
- // TODO(teboring): Add it back.
- // memset(memory, 0, NATIVE_SLOT_MAX_SIZE);
- // *oneof_case = ONEOF_CASE_NONE;
- } else if (is_map_field(field)) {
- // TODO(teboring): Add it back.
- // VALUE map = Qnil;
-
- // const upb_fielddef* key_field = map_field_key(field);
- // const upb_fielddef* value_field = map_field_value(field);
- // VALUE type_class = field_type_class(value_field);
-
- // if (type_class != Qnil) {
- // VALUE args[3] = {
- // fieldtype_to_php(upb_fielddef_type(key_field)),
- // fieldtype_to_php(upb_fielddef_type(value_field)), type_class,
- // };
- // map = php_class_new_instance(3, args, cMap);
- // } else {
- // VALUE args[2] = {
- // fieldtype_to_php(upb_fielddef_type(key_field)),
- // fieldtype_to_php(upb_fielddef_type(value_field)),
- // };
- // map = php_class_new_instance(2, args, cMap);
- // }
-
- // DEREF(memory, VALUE) = map;
- } else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
- // TODO(teboring): Add it back.
- // VALUE ary = Qnil;
-
- // VALUE type_class = field_type_class(field);
-
- // if (type_class != Qnil) {
- // VALUE args[2] = {
- // fieldtype_to_php(upb_fielddef_type(field)), type_class,
- // };
- // ary = php_class_new_instance(2, args, cRepeatedField);
- // } else {
- // VALUE args[1] = {fieldtype_to_php(upb_fielddef_type(field))};
- // ary = php_class_new_instance(1, args, cRepeatedField);
- // }
-
- // DEREF(memory, VALUE) = ary;
- } else {
- native_slot_init(upb_fielddef_type(field), memory);
- }
- }
-}
-
-zval* layout_get(MessageLayout* layout, const void* storage,
- const upb_fielddef* field TSRMLS_DC) {
+void layout_set(MessageLayout* layout, MessageHeader* header,
+ const upb_fielddef* field, zval* val TSRMLS_DC) {
+ void* storage = message_data(header);
void* memory = slot_memory(layout, storage, field);
uint32_t* oneof_case = slot_oneof_case(layout, storage, field);
if (upb_fielddef_containingoneof(field)) {
- if (*oneof_case != upb_fielddef_number(field)) {
- return NULL;
- // TODO(teboring): Add it back.
- // return Qnil;
+ upb_fieldtype_t type = upb_fielddef_type(field);
+ zend_class_entry *ce = NULL;
+
+ // For non-singular fields, the related memory needs to point to the actual
+ // zval in properties table first.
+ switch (type) {
+ case UPB_TYPE_MESSAGE: {
+ const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
+ zval* desc_php = get_def_obj(msg);
+ Descriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ ce = desc->klass;
+ // Intentionally fall through.
+ }
+ case UPB_TYPE_STRING:
+ case UPB_TYPE_BYTES: {
+ int property_cache_index =
+ header->descriptor->layout->fields[upb_fielddef_index(field)]
+ .cache_index;
+ DEREF(memory, zval**) =
+ &(header->std.properties_table)[property_cache_index];
+ memory = DEREF(memory, zval**);
+ break;
+ }
+ default:
+ break;
}
- return NULL;
- // TODO(teboring): Add it back.
- // return native_slot_get(upb_fielddef_type(field), field_type_class(field),
- // memory);
+
+ native_slot_set(type, ce, memory, val TSRMLS_CC);
+ *oneof_case = upb_fielddef_number(field);
} else if (upb_fielddef_label(field) == UPB_LABEL_REPEATED) {
- return NULL;
- // TODO(teboring): Add it back.
- // return *((VALUE*)memory);
+ // Works for both repeated and map fields
+ memory = DEREF(memory, zval**);
+ if (EXPECTED(DEREF(memory, zval*) != val)) {
+ zval_ptr_dtor(memory);
+ DEREF(memory, zval*) = val;
+ Z_ADDREF_P(val);
+ }
} else {
- return native_slot_get(
- upb_fielddef_type(field), /*field_type_class(field), */
- memory TSRMLS_CC);
+ upb_fieldtype_t type = upb_fielddef_type(field);
+ zend_class_entry *ce = NULL;
+ if (type == UPB_TYPE_MESSAGE) {
+ const upb_msgdef* msg = upb_fielddef_msgsubdef(field);
+ zval* desc_php = get_def_obj(msg);
+ Descriptor* desc = zend_object_store_get_object(desc_php TSRMLS_CC);
+ ce = desc->klass;
+ }
+ native_slot_set(type, ce, value_memory(field, memory), val TSRMLS_CC);
}
}
diff --git a/php/ext/google/protobuf/test.php b/php/ext/google/protobuf/test.php
deleted file mode 100644
index 6bbadd48..00000000
--- a/php/ext/google/protobuf/test.php
+++ /dev/null
@@ -1,15 +0,0 @@
-<?php
-
-
-namespace Google\Protobuf;
-
-$pool = get_generated_pool();
-$pool->addMessage("TestMessage")
- ->optional("optional_int32_a", "int32", 1)
- ->optional("optional_int32_b", "int32", 2)
- ->finalizeToPool()
- ->finalize();
-
-$test_message = new \TestMessage();
-
-?>
diff --git a/php/ext/google/protobuf/type_check.c b/php/ext/google/protobuf/type_check.c
new file mode 100644
index 00000000..d12d0025
--- /dev/null
+++ b/php/ext/google/protobuf/type_check.c
@@ -0,0 +1,430 @@
+// 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 <Zend/zend_operators.h>
+
+#include "protobuf.h"
+#include "utf8.h"
+
+static zend_class_entry* util_type;
+static const char int64_min_digits[] = "9223372036854775808";
+
+ZEND_BEGIN_ARG_INFO_EX(arg_check_optional, 0, 0, 1)
+ ZEND_ARG_INFO(1, val)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arg_check_message, 0, 0, 2)
+ ZEND_ARG_INFO(1, val)
+ ZEND_ARG_INFO(0, klass)
+ZEND_END_ARG_INFO()
+
+ZEND_BEGIN_ARG_INFO_EX(arg_check_repeated, 0, 0, 2)
+ ZEND_ARG_INFO(1, val)
+ ZEND_ARG_INFO(0, type)
+ ZEND_ARG_INFO(0, klass)
+ZEND_END_ARG_INFO()
+
+static zend_function_entry util_methods[] = {
+ PHP_ME(Util, checkInt32, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkUint32, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkInt64, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkUint64, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkEnum, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkFloat, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkDouble, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkBool, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkString, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkBytes, arg_check_optional, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkMessage, arg_check_message, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ PHP_ME(Util, checkRepeatedField, arg_check_repeated,
+ ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
+ ZEND_FE_END
+};
+
+void util_init(TSRMLS_D) {
+ zend_class_entry class_type;
+ INIT_CLASS_ENTRY(class_type, "Google\\Protobuf\\Internal\\GPBUtil",
+ util_methods);
+ util_type = zend_register_internal_class(&class_type TSRMLS_CC);
+}
+
+// -----------------------------------------------------------------------------
+// Type checking/conversion.
+// -----------------------------------------------------------------------------
+
+// This is modified from is_numeric_string in zend_operators.h. The behavior of
+// this function is the same as is_numeric_string, except that this takes
+// int64_t as input instead of long.
+static zend_uchar convert_numeric_string(
+ const char *str, int length, int64_t *lval, double *dval) {
+ const char *ptr;
+ int base = 10, digits = 0, dp_or_e = 0;
+ double local_dval = 0.0;
+ zend_uchar type;
+
+ if (length == 0) {
+ return IS_NULL;
+ }
+
+ while (*str == ' ' || *str == '\t' || *str == '\n' ||
+ *str == '\r' || *str == '\v' || *str == '\f') {
+ str++;
+ length--;
+ }
+ ptr = str;
+
+ if (*ptr == '-' || *ptr == '+') {
+ ptr++;
+ }
+
+ if (ZEND_IS_DIGIT(*ptr)) {
+ // Handle hex numbers
+ // str is used instead of ptr to disallow signs and keep old behavior.
+ if (length > 2 && *str == '0' && (str[1] == 'x' || str[1] == 'X')) {
+ base = 16;
+ ptr += 2;
+ }
+
+ // Skip any leading 0s.
+ while (*ptr == '0') {
+ ptr++;
+ }
+
+ // Count the number of digits. If a decimal point/exponent is found,
+ // it's a double. Otherwise, if there's a dval or no need to check for
+ // a full match, stop when there are too many digits for a int64 */
+ for (type = IS_LONG;
+ !(digits >= MAX_LENGTH_OF_INT64 && dval);
+ digits++, ptr++) {
+check_digits:
+ if (ZEND_IS_DIGIT(*ptr) || (base == 16 && ZEND_IS_XDIGIT(*ptr))) {
+ continue;
+ } else if (base == 10) {
+ if (*ptr == '.' && dp_or_e < 1) {
+ goto process_double;
+ } else if ((*ptr == 'e' || *ptr == 'E') && dp_or_e < 2) {
+ const char *e = ptr + 1;
+
+ if (*e == '-' || *e == '+') {
+ ptr = e++;
+ }
+ if (ZEND_IS_DIGIT(*e)) {
+ goto process_double;
+ }
+ }
+ }
+ break;
+ }
+
+ if (base == 10) {
+ if (digits >= MAX_LENGTH_OF_INT64) {
+ dp_or_e = -1;
+ goto process_double;
+ }
+ } else if (!(digits < SIZEOF_INT64 * 2 ||
+ (digits == SIZEOF_INT64 * 2 && ptr[-digits] <= '7'))) {
+ if (dval) {
+ local_dval = zend_hex_strtod(str, &ptr);
+ }
+ type = IS_DOUBLE;
+ }
+ } else if (*ptr == '.' && ZEND_IS_DIGIT(ptr[1])) {
+process_double:
+ type = IS_DOUBLE;
+
+ // If there's a dval, do the conversion; else continue checking
+ // the digits if we need to check for a full match.
+ if (dval) {
+ local_dval = zend_strtod(str, &ptr);
+ } else if (dp_or_e != -1) {
+ dp_or_e = (*ptr++ == '.') ? 1 : 2;
+ goto check_digits;
+ }
+ } else {
+ return IS_NULL;
+ }
+ if (ptr != str + length) {
+ zend_error(E_NOTICE, "A non well formed numeric value encountered");
+ return 0;
+ }
+
+ if (type == IS_LONG) {
+ if (digits == MAX_LENGTH_OF_INT64 - 1) {
+ int cmp = strcmp(&ptr[-digits], int64_min_digits);
+
+ if (!(cmp < 0 || (cmp == 0 && *str == '-'))) {
+ if (dval) {
+ *dval = zend_strtod(str, NULL);
+ }
+
+ return IS_DOUBLE;
+ }
+ }
+ if (lval) {
+ *lval = strtoll(str, NULL, base);
+ }
+ return IS_LONG;
+ } else {
+ if (dval) {
+ *dval = local_dval;
+ }
+ return IS_DOUBLE;
+ }
+}
+
+#define CONVERT_TO_INTEGER(type) \
+ static bool convert_int64_to_##type(int64_t val, type##_t* type##_value) { \
+ *type##_value = (type##_t)val; \
+ return true; \
+ } \
+ \
+ static bool convert_double_to_##type(double val, type##_t* type##_value) { \
+ *type##_value = (type##_t)zend_dval_to_lval(val); \
+ return true; \
+ } \
+ \
+ static bool convert_string_to_##type(const char* val, int len, \
+ type##_t* type##_value) { \
+ int64_t lval; \
+ double dval; \
+ \
+ switch (convert_numeric_string(val, len, &lval, &dval)) { \
+ case IS_DOUBLE: { \
+ return convert_double_to_##type(dval, type##_value); \
+ } \
+ case IS_LONG: { \
+ return convert_int64_to_##type(lval, type##_value); \
+ } \
+ default: \
+ zend_error(E_USER_ERROR, \
+ "Given string value cannot be converted to integer."); \
+ return false; \
+ } \
+ } \
+ \
+ bool protobuf_convert_to_##type(zval* from, type##_t* to) { \
+ switch (Z_TYPE_P(from)) { \
+ case IS_LONG: { \
+ return convert_int64_to_##type(Z_LVAL_P(from), to); \
+ } \
+ case IS_DOUBLE: { \
+ return convert_double_to_##type(Z_DVAL_P(from), to); \
+ } \
+ case IS_STRING: { \
+ return convert_string_to_##type(Z_STRVAL_P(from), Z_STRLEN_P(from), \
+ to); \
+ } \
+ default: { \
+ zend_error(E_USER_ERROR, \
+ "Given value cannot be converted to integer."); \
+ return false; \
+ } \
+ } \
+ return false; \
+ }
+
+CONVERT_TO_INTEGER(int32);
+CONVERT_TO_INTEGER(uint32);
+CONVERT_TO_INTEGER(int64);
+CONVERT_TO_INTEGER(uint64);
+
+#undef CONVERT_TO_INTEGER
+
+#define CONVERT_TO_FLOAT(type) \
+ static bool convert_int64_to_##type(int64_t val, type* type##_value) { \
+ *type##_value = (type)val; \
+ return true; \
+ } \
+ \
+ static bool convert_double_to_##type(double val, type* type##_value) { \
+ *type##_value = (type)val; \
+ return true; \
+ } \
+ \
+ static bool convert_string_to_##type(const char* val, int len, \
+ type* type##_value) { \
+ int64_t lval; \
+ double dval; \
+ \
+ switch (convert_numeric_string(val, len, &lval, &dval)) { \
+ case IS_DOUBLE: { \
+ *type##_value = (type)dval; \
+ return true; \
+ } \
+ case IS_LONG: { \
+ *type##_value = (type)lval; \
+ return true; \
+ } \
+ default: \
+ zend_error(E_USER_ERROR, \
+ "Given string value cannot be converted to integer."); \
+ return false; \
+ } \
+ } \
+ \
+ bool protobuf_convert_to_##type(zval* from, type* to) { \
+ switch (Z_TYPE_P(from)) { \
+ case IS_LONG: { \
+ return convert_int64_to_##type(Z_LVAL_P(from), to); \
+ } \
+ case IS_DOUBLE: { \
+ return convert_double_to_##type(Z_DVAL_P(from), to); \
+ } \
+ case IS_STRING: { \
+ return convert_string_to_##type(Z_STRVAL_P(from), Z_STRLEN_P(from), \
+ to); \
+ } \
+ default: { \
+ zend_error(E_USER_ERROR, \
+ "Given value cannot be converted to integer."); \
+ return false; \
+ } \
+ } \
+ return false; \
+ }
+
+CONVERT_TO_FLOAT(float);
+CONVERT_TO_FLOAT(double);
+
+#undef CONVERT_TO_FLOAT
+
+bool protobuf_convert_to_bool(zval* from, int8_t* to) {
+ switch (Z_TYPE_P(from)) {
+ case IS_BOOL:
+ *to = (int8_t)Z_BVAL_P(from);
+ break;
+ case IS_LONG:
+ *to = (int8_t)(Z_LVAL_P(from) != 0);
+ break;
+ case IS_DOUBLE:
+ *to = (int8_t)(Z_LVAL_P(from) != 0);
+ break;
+ case IS_STRING: {
+ char* strval = Z_STRVAL_P(from);
+
+ if (Z_STRLEN_P(from) == 0 ||
+ (Z_STRLEN_P(from) == 1 && Z_STRVAL_P(from)[0] == '0')) {
+ *to = 0;
+ } else {
+ *to = 1;
+ }
+ } break;
+ default: {
+ zend_error(E_USER_ERROR, "Given value cannot be converted to bool.");
+ return false;
+ }
+ }
+ return true;
+}
+
+bool protobuf_convert_to_string(zval* from) {
+ switch (Z_TYPE_P(from)) {
+ case IS_STRING: {
+ return true;
+ }
+ case IS_BOOL:
+ case IS_LONG:
+ case IS_DOUBLE: {
+ int use_copy;
+ zval tmp;
+ zend_make_printable_zval(from, &tmp, &use_copy);
+ ZVAL_COPY_VALUE(from, &tmp);
+ return true;
+ }
+ default:
+ zend_error(E_USER_ERROR, "Given value cannot be converted to string.");
+ return false;
+ }
+}
+
+// -----------------------------------------------------------------------------
+// PHP Functions.
+// -----------------------------------------------------------------------------
+
+// The implementation of type checking for primitive fields is empty. This is
+// because type checking is done when direct assigning message fields (e.g.,
+// foo->a = 1). Functions defined here are place holders in generated code for
+// pure PHP implementation (c extension and pure PHP share the same generated
+// code).
+#define PHP_TYPE_CHECK(type) \
+ PHP_METHOD(Util, check##type) {}
+
+PHP_TYPE_CHECK(Int32)
+PHP_TYPE_CHECK(Uint32)
+PHP_TYPE_CHECK(Int64)
+PHP_TYPE_CHECK(Uint64)
+PHP_TYPE_CHECK(Enum)
+PHP_TYPE_CHECK(Float)
+PHP_TYPE_CHECK(Double)
+PHP_TYPE_CHECK(Bool)
+PHP_TYPE_CHECK(String)
+PHP_TYPE_CHECK(Bytes)
+
+#undef PHP_TYPE_CHECK
+
+PHP_METHOD(Util, checkMessage) {
+ zval* val;
+ zend_class_entry* klass = NULL;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o!C", &val, &klass) ==
+ FAILURE) {
+ return;
+ }
+ if (val == NULL) {
+ RETURN_NULL();
+ }
+ if (!instanceof_function(Z_OBJCE_P(val), klass TSRMLS_CC)) {
+ zend_error(E_USER_ERROR, "Given value is not an instance of %s.",
+ klass->name);
+ return;
+ }
+ RETURN_ZVAL(val, 1, 0);
+}
+
+PHP_METHOD(Util, checkRepeatedField) {
+ zval* val;
+ long type;
+ const zend_class_entry* klass = NULL;
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Ol|C", &val,
+ repeated_field_type, &type, &klass) == FAILURE) {
+ return;
+ }
+
+ RepeatedField *intern =
+ (RepeatedField *)zend_object_store_get_object(val TSRMLS_CC);
+ if (to_fieldtype(type) != intern->type) {
+ zend_error(E_USER_ERROR, "Incorrect repeated field type.");
+ return;
+ }
+ if (klass != NULL && intern->msg_ce != klass) {
+ zend_error(E_USER_ERROR, "Expect a repeated field of %s, but %s is given.",
+ klass->name, intern->msg_ce->name);
+ return;
+ }
+}
diff --git a/php/ext/google/protobuf/upb.c b/php/ext/google/protobuf/upb.c
index 048a163a..98daafc0 100644
--- a/php/ext/google/protobuf/upb.c
+++ b/php/ext/google/protobuf/upb.c
@@ -1,7 +1,37 @@
-// Amalgamated source file
+// 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 "upb.h"
+#include <ctype.h>
#include <stdlib.h>
#include <string.h>
@@ -11,7 +41,7 @@ typedef struct {
} str_t;
static str_t *newstr(const char *data, size_t len) {
- str_t *ret = malloc(sizeof(*ret) + len);
+ str_t *ret = upb_gmalloc(sizeof(*ret) + len);
if (!ret) return NULL;
ret->len = len;
memcpy(ret->str, data, len);
@@ -19,7 +49,7 @@ static str_t *newstr(const char *data, size_t len) {
return ret;
}
-static void freestr(str_t *s) { free(s); }
+static void freestr(str_t *s) { upb_gfree(s); }
/* isalpha() etc. from <ctype.h> are locale-dependent, which we don't want. */
static bool upb_isbetween(char c, char low, char high) {
@@ -64,6 +94,22 @@ static bool upb_isident(const char *str, size_t len, bool full, upb_status *s) {
return !start;
}
+static bool upb_isoneof(const upb_refcounted *def) {
+ return def->vtbl == &upb_oneofdef_vtbl;
+}
+
+static bool upb_isfield(const upb_refcounted *def) {
+ return def->vtbl == &upb_fielddef_vtbl;
+}
+
+static const upb_oneofdef *upb_trygetoneof(const upb_refcounted *def) {
+ return upb_isoneof(def) ? (const upb_oneofdef*)def : NULL;
+}
+
+static const upb_fielddef *upb_trygetfield(const upb_refcounted *def) {
+ return upb_isfield(def) ? (const upb_fielddef*)def : NULL;
+}
+
/* upb_def ********************************************************************/
@@ -71,14 +117,39 @@ upb_deftype_t upb_def_type(const upb_def *d) { return d->type; }
const char *upb_def_fullname(const upb_def *d) { return d->fullname; }
+const char *upb_def_name(const upb_def *d) {
+ const char *p;
+
+ if (d->fullname == NULL) {
+ return NULL;
+ } else if ((p = strrchr(d->fullname, '.')) == NULL) {
+ /* No '.' in the name, return the full string. */
+ return d->fullname;
+ } else {
+ /* Return one past the last '.'. */
+ return p + 1;
+ }
+}
+
bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s) {
- assert(!upb_def_isfrozen(def));
- if (!upb_isident(fullname, strlen(fullname), true, s)) return false;
- free((void*)def->fullname);
- def->fullname = upb_strdup(fullname);
+ UPB_ASSERT(!upb_def_isfrozen(def));
+ if (!upb_isident(fullname, strlen(fullname), true, s)) {
+ return false;
+ }
+
+ fullname = upb_gstrdup(fullname);
+ if (!fullname) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+
+ upb_gfree((void*)def->fullname);
+ def->fullname = fullname;
return true;
}
+const upb_filedef *upb_def_file(const upb_def *d) { return d->file; }
+
upb_def *upb_def_dup(const upb_def *def, const void *o) {
switch (def->type) {
case UPB_DEF_MSG:
@@ -90,7 +161,7 @@ upb_def *upb_def_dup(const upb_def *def, const void *o) {
case UPB_DEF_ENUM:
return upb_enumdef_upcast_mutable(
upb_enumdef_dup(upb_downcast_enumdef(def), o));
- default: assert(false); return NULL;
+ default: UPB_ASSERT(false); return NULL;
}
}
@@ -101,11 +172,12 @@ static bool upb_def_init(upb_def *def, upb_deftype_t type,
def->type = type;
def->fullname = NULL;
def->came_from_user = false;
+ def->file = NULL;
return true;
}
static void upb_def_uninit(upb_def *def) {
- free((void*)def->fullname);
+ upb_gfree((void*)def->fullname);
}
static const char *msgdef_name(const upb_msgdef *m) {
@@ -160,14 +232,14 @@ static bool upb_validate_field(upb_fielddef *f, upb_status *s) {
bool has_default_number = upb_fielddef_enumhasdefaultint32(f);
/* Previously verified by upb_validate_enumdef(). */
- assert(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
+ UPB_ASSERT(upb_enumdef_numvals(upb_fielddef_enumsubdef(f)) > 0);
/* We've already validated that we have an associated enumdef and that it
* has at least one member, so at least one of these should be true.
* Because if the user didn't set anything, we'll pick up the enum's
* default, but if the user *did* set something we should at least pick up
* the one they set (int32 or string). */
- assert(has_default_name || has_default_number);
+ UPB_ASSERT(has_default_name || has_default_number);
if (!has_default_name) {
upb_status_seterrf(s,
@@ -223,7 +295,7 @@ static bool upb_validate_enumdef(const upb_enumdef *e, upb_status *s) {
uint32_t field_rank(const upb_fielddef *f) {
uint32_t ret = upb_fielddef_number(f);
const uint32_t high_bit = 1 << 30;
- assert(ret < high_bit);
+ UPB_ASSERT(ret < high_bit);
if (!upb_fielddef_issubmsg(f))
ret |= high_bit;
return ret;
@@ -242,17 +314,28 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
int i;
uint32_t selector;
int n = upb_msgdef_numfields(m);
- upb_fielddef **fields = malloc(n * sizeof(*fields));
- if (!fields) return false;
+ upb_fielddef **fields;
+
+ if (n == 0) {
+ m->selector_count = UPB_STATIC_SELECTOR_COUNT;
+ m->submsg_field_count = 0;
+ return true;
+ }
+
+ fields = upb_gmalloc(n * sizeof(*fields));
+ if (!fields) {
+ upb_upberr_setoom(s);
+ return false;
+ }
m->submsg_field_count = 0;
for(i = 0, upb_msg_field_begin(&j, m);
!upb_msg_field_done(&j);
upb_msg_field_next(&j), i++) {
upb_fielddef *f = upb_msg_iter_field(&j);
- assert(f->msg.def == m);
+ UPB_ASSERT(f->msg.def == m);
if (!upb_validate_field(f, s)) {
- free(fields);
+ upb_gfree(fields);
return false;
}
if (upb_fielddef_issubmsg(f)) {
@@ -312,15 +395,12 @@ static bool assign_msg_indices(upb_msgdef *m, upb_status *s) {
#undef TRY
#endif
- free(fields);
+ upb_gfree(fields);
return true;
}
-bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
- int i;
- int maxdepth;
- bool ret;
- upb_status_clear(s);
+bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s) {
+ size_t i;
/* First perform validation, in two passes so we can check that we have a
* transitive closure without needing to search. */
@@ -346,8 +426,9 @@ bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
/* Second pass of validation. Also assign selector bases and indexes, and
* compact tables. */
for (i = 0; i < n; i++) {
- upb_msgdef *m = upb_dyncast_msgdef_mutable(defs[i]);
- upb_enumdef *e = upb_dyncast_enumdef_mutable(defs[i]);
+ upb_def *def = defs[i];
+ upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
+ upb_enumdef *e = upb_dyncast_enumdef_mutable(def);
if (m) {
upb_inttable_compact(&m->itof);
if (!assign_msg_indices(m, s)) {
@@ -358,46 +439,68 @@ bool upb_def_freeze(upb_def *const* defs, int n, upb_status *s) {
}
}
- /* Def graph contains FieldDefs between each MessageDef, so double the
- * limit. */
- maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
-
- /* Validation all passed; freeze the defs. */
- ret = upb_refcounted_freeze((upb_refcounted * const *)defs, n, s, maxdepth);
- assert(!(s && ret != upb_ok(s)));
- return ret;
+ return true;
err:
for (i = 0; i < n; i++) {
- defs[i]->came_from_user = false;
+ upb_def *def = defs[i];
+ def->came_from_user = false;
}
- assert(!(s && upb_ok(s)));
+ UPB_ASSERT(!(s && upb_ok(s)));
return false;
}
+bool upb_def_freeze(upb_def *const* defs, size_t n, upb_status *s) {
+ /* Def graph contains FieldDefs between each MessageDef, so double the
+ * limit. */
+ const size_t maxdepth = UPB_MAX_MESSAGE_DEPTH * 2;
+
+ if (!_upb_def_validate(defs, n, s)) {
+ return false;
+ }
+
+
+ /* Validation all passed; freeze the objects. */
+ return upb_refcounted_freeze((upb_refcounted *const*)defs, n, s, maxdepth);
+}
+
/* upb_enumdef ****************************************************************/
-static void upb_enumdef_free(upb_refcounted *r) {
+static void visitenum(const upb_refcounted *r, upb_refcounted_visit *visit,
+ void *closure) {
+ const upb_enumdef *e = (const upb_enumdef*)r;
+ const upb_def *def = upb_enumdef_upcast(e);
+ if (upb_def_file(def)) {
+ visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
+ }
+}
+
+static void freeenum(upb_refcounted *r) {
upb_enumdef *e = (upb_enumdef*)r;
upb_inttable_iter i;
upb_inttable_begin(&i, &e->iton);
for( ; !upb_inttable_done(&i); upb_inttable_next(&i)) {
- /* To clean up the upb_strdup() from upb_enumdef_addval(). */
- free(upb_value_getcstr(upb_inttable_iter_value(&i)));
+ /* To clean up the upb_gstrdup() from upb_enumdef_addval(). */
+ upb_gfree(upb_value_getcstr(upb_inttable_iter_value(&i)));
}
upb_strtable_uninit(&e->ntoi);
upb_inttable_uninit(&e->iton);
upb_def_uninit(upb_enumdef_upcast_mutable(e));
- free(e);
+ upb_gfree(e);
}
+const struct upb_refcounted_vtbl upb_enumdef_vtbl = {&visitenum, &freeenum};
+
upb_enumdef *upb_enumdef_new(const void *owner) {
- static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_enumdef_free};
- upb_enumdef *e = malloc(sizeof(*e));
+ upb_enumdef *e = upb_gmalloc(sizeof(*e));
if (!e) return NULL;
- if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM, &vtbl, owner))
+
+ if (!upb_def_init(upb_enumdef_upcast_mutable(e), UPB_DEF_ENUM,
+ &upb_enumdef_vtbl, owner)) {
goto err2;
+ }
+
if (!upb_strtable_init(&e->ntoi, UPB_CTYPE_INT32)) goto err2;
if (!upb_inttable_init(&e->iton, UPB_CTYPE_CSTR)) goto err1;
return e;
@@ -405,7 +508,7 @@ upb_enumdef *upb_enumdef_new(const void *owner) {
err1:
upb_strtable_uninit(&e->ntoi);
err2:
- free(e);
+ upb_gfree(e);
return NULL;
}
@@ -433,6 +536,10 @@ const char *upb_enumdef_fullname(const upb_enumdef *e) {
return upb_def_fullname(upb_enumdef_upcast(e));
}
+const char *upb_enumdef_name(const upb_enumdef *e) {
+ return upb_def_name(upb_enumdef_upcast(e));
+}
+
bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
upb_status *s) {
return upb_def_setfullname(upb_enumdef_upcast_mutable(e), fullname, s);
@@ -440,37 +547,46 @@ bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
bool upb_enumdef_addval(upb_enumdef *e, const char *name, int32_t num,
upb_status *status) {
+ char *name2;
+
if (!upb_isident(name, strlen(name), false, status)) {
return false;
}
+
if (upb_enumdef_ntoiz(e, name, NULL)) {
upb_status_seterrf(status, "name '%s' is already defined", name);
return false;
}
+
if (!upb_strtable_insert(&e->ntoi, name, upb_value_int32(num))) {
upb_status_seterrmsg(status, "out of memory");
return false;
}
- if (!upb_inttable_lookup(&e->iton, num, NULL) &&
- !upb_inttable_insert(&e->iton, num, upb_value_cstr(upb_strdup(name)))) {
- upb_status_seterrmsg(status, "out of memory");
- upb_strtable_remove(&e->ntoi, name, NULL);
- return false;
+
+ if (!upb_inttable_lookup(&e->iton, num, NULL)) {
+ name2 = upb_gstrdup(name);
+ if (!name2 || !upb_inttable_insert(&e->iton, num, upb_value_cstr(name2))) {
+ upb_status_seterrmsg(status, "out of memory");
+ upb_strtable_remove(&e->ntoi, name, NULL);
+ return false;
+ }
}
+
if (upb_enumdef_numvals(e) == 1) {
bool ok = upb_enumdef_setdefault(e, num, NULL);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
}
+
return true;
}
int32_t upb_enumdef_default(const upb_enumdef *e) {
- assert(upb_enumdef_iton(e, e->defaultval));
+ UPB_ASSERT(upb_enumdef_iton(e, e->defaultval));
return e->defaultval;
}
bool upb_enumdef_setdefault(upb_enumdef *e, int32_t val, upb_status *s) {
- assert(!upb_enumdef_isfrozen(e));
+ UPB_ASSERT(!upb_enumdef_isfrozen(e));
if (!upb_enumdef_iton(e, val)) {
upb_status_seterrf(s, "number '%d' is not in the enum.", val);
return false;
@@ -525,32 +641,40 @@ static void upb_fielddef_uninit_default(upb_fielddef *f) {
freestr(f->defaultval.bytes);
}
+const char *upb_fielddef_fullname(const upb_fielddef *e) {
+ return upb_def_fullname(upb_fielddef_upcast(e));
+}
+
static void visitfield(const upb_refcounted *r, upb_refcounted_visit *visit,
void *closure) {
const upb_fielddef *f = (const upb_fielddef*)r;
+ const upb_def *def = upb_fielddef_upcast(f);
if (upb_fielddef_containingtype(f)) {
visit(r, upb_msgdef_upcast2(upb_fielddef_containingtype(f)), closure);
}
if (upb_fielddef_containingoneof(f)) {
- visit(r, upb_oneofdef_upcast2(upb_fielddef_containingoneof(f)), closure);
+ visit(r, upb_oneofdef_upcast(upb_fielddef_containingoneof(f)), closure);
}
if (upb_fielddef_subdef(f)) {
visit(r, upb_def_upcast(upb_fielddef_subdef(f)), closure);
}
+ if (upb_def_file(def)) {
+ visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
+ }
}
static void freefield(upb_refcounted *r) {
upb_fielddef *f = (upb_fielddef*)r;
upb_fielddef_uninit_default(f);
if (f->subdef_is_symbolic)
- free(f->sub.name);
+ upb_gfree(f->sub.name);
upb_def_uninit(upb_fielddef_upcast_mutable(f));
- free(f);
+ upb_gfree(f);
}
static const char *enumdefaultstr(const upb_fielddef *f) {
const upb_enumdef *e;
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
e = upb_fielddef_enumsubdef(f);
if (f->default_is_string && f->defaultval.bytes) {
/* Default was explicitly set as a string. */
@@ -567,7 +691,7 @@ static const char *enumdefaultstr(const upb_fielddef *f) {
/* Default is completely unset; pull enumdef default. */
if (upb_enumdef_numvals(e) > 0) {
const char *name = upb_enumdef_iton(e, upb_enumdef_default(e));
- assert(name);
+ UPB_ASSERT(name);
return name;
}
}
@@ -577,7 +701,7 @@ static const char *enumdefaultstr(const upb_fielddef *f) {
static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
const upb_enumdef *e;
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
e = upb_fielddef_enumsubdef(f);
if (!f->default_is_string) {
/* Default was explicitly set as an integer. */
@@ -601,12 +725,14 @@ static bool enumdefaultint32(const upb_fielddef *f, int32_t *val) {
return false;
}
+const struct upb_refcounted_vtbl upb_fielddef_vtbl = {visitfield, freefield};
+
upb_fielddef *upb_fielddef_new(const void *o) {
- static const struct upb_refcounted_vtbl vtbl = {visitfield, freefield};
- upb_fielddef *f = malloc(sizeof(*f));
+ upb_fielddef *f = upb_gmalloc(sizeof(*f));
if (!f) return NULL;
- if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD, &vtbl, o)) {
- free(f);
+ if (!upb_def_init(upb_fielddef_upcast_mutable(f), UPB_DEF_FIELD,
+ &upb_fielddef_vtbl, o)) {
+ upb_gfree(f);
return NULL;
}
f->msg.def = NULL;
@@ -657,7 +783,7 @@ upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
srcname = f->sub.def ? upb_def_fullname(f->sub.def) : NULL;
}
if (srcname) {
- char *newname = malloc(strlen(f->sub.def->fullname) + 2);
+ char *newname = upb_gmalloc(strlen(f->sub.def->fullname) + 2);
if (!newname) {
upb_fielddef_unref(newf, owner);
return NULL;
@@ -665,7 +791,7 @@ upb_fielddef *upb_fielddef_dup(const upb_fielddef *f, const void *owner) {
strcpy(newname, ".");
strcat(newname, f->sub.def->fullname);
upb_fielddef_setsubdefname(newf, newname, NULL);
- free(newname);
+ upb_gfree(newname);
}
return newf;
@@ -676,7 +802,7 @@ bool upb_fielddef_typeisset(const upb_fielddef *f) {
}
upb_fieldtype_t upb_fielddef_type(const upb_fielddef *f) {
- assert(f->type_is_set_);
+ UPB_ASSERT(f->type_is_set_);
return f->type_;
}
@@ -716,6 +842,45 @@ const char *upb_fielddef_name(const upb_fielddef *f) {
return upb_def_fullname(upb_fielddef_upcast(f));
}
+size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len) {
+ const char *name = upb_fielddef_name(f);
+ size_t src, dst = 0;
+ bool ucase_next = false;
+
+#define WRITE(byte) \
+ ++dst; \
+ if (dst < len) buf[dst - 1] = byte; \
+ else if (dst == len) buf[dst - 1] = '\0'
+
+ if (!name) {
+ WRITE('\0');
+ return 0;
+ }
+
+ /* Implement the transformation as described in the spec:
+ * 1. upper case all letters after an underscore.
+ * 2. remove all underscores.
+ */
+ for (src = 0; name[src]; src++) {
+ if (name[src] == '_') {
+ ucase_next = true;
+ continue;
+ }
+
+ if (ucase_next) {
+ WRITE(toupper(name[src]));
+ ucase_next = false;
+ } else {
+ WRITE(name[src]);
+ }
+ }
+
+ WRITE('\0');
+ return dst;
+
+#undef WRITE
+}
+
const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f) {
return f->msg_is_symbolic ? NULL : f->msg.def;
}
@@ -733,20 +898,28 @@ const char *upb_fielddef_containingtypename(upb_fielddef *f) {
}
static void release_containingtype(upb_fielddef *f) {
- if (f->msg_is_symbolic) free(f->msg.name);
+ if (f->msg_is_symbolic) upb_gfree(f->msg.name);
}
bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
upb_status *s) {
- assert(!upb_fielddef_isfrozen(f));
+ char *name_copy;
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
if (upb_fielddef_containingtype(f)) {
upb_status_seterrmsg(s, "field has already been added to a message.");
return false;
}
/* TODO: validate name (upb_isident() doesn't quite work atm because this name
* may have a leading "."). */
+
+ name_copy = upb_gstrdup(name);
+ if (!name_copy) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+
release_containingtype(f);
- f->msg.name = upb_strdup(name);
+ f->msg.name = name_copy;
f->msg_is_symbolic = true;
return true;
}
@@ -762,7 +935,7 @@ bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s) {
static void chkdefaulttype(const upb_fielddef *f, upb_fieldtype_t type) {
UPB_UNUSED(f);
UPB_UNUSED(type);
- assert(f->type_is_set_ && upb_fielddef_type(f) == type);
+ UPB_ASSERT(f->type_is_set_ && upb_fielddef_type(f) == type);
}
int64_t upb_fielddef_defaultint64(const upb_fielddef *f) {
@@ -774,7 +947,7 @@ int32_t upb_fielddef_defaultint32(const upb_fielddef *f) {
if (f->type_is_set_ && upb_fielddef_type(f) == UPB_TYPE_ENUM) {
int32_t val;
bool ok = enumdefaultint32(f, &val);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return val;
} else {
chkdefaulttype(f, UPB_TYPE_INT32);
@@ -808,14 +981,14 @@ double upb_fielddef_defaultdouble(const upb_fielddef *f) {
}
const char *upb_fielddef_defaultstr(const upb_fielddef *f, size_t *len) {
- assert(f->type_is_set_);
- assert(upb_fielddef_type(f) == UPB_TYPE_STRING ||
+ UPB_ASSERT(f->type_is_set_);
+ UPB_ASSERT(upb_fielddef_type(f) == UPB_TYPE_STRING ||
upb_fielddef_type(f) == UPB_TYPE_BYTES ||
upb_fielddef_type(f) == UPB_TYPE_ENUM);
if (upb_fielddef_type(f) == UPB_TYPE_ENUM) {
const char *ret = enumdefaultstr(f);
- assert(ret);
+ UPB_ASSERT(ret);
/* Enum defaults can't have embedded NULLs. */
if (len) *len = strlen(ret);
return ret;
@@ -897,8 +1070,8 @@ bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s) {
}
void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_checktype(type));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_checktype(type));
upb_fielddef_uninit_default(f);
f->type_ = type;
f->type_is_set_ = true;
@@ -906,7 +1079,7 @@ void upb_fielddef_settype(upb_fielddef *f, upb_fieldtype_t type) {
}
void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
switch (type) {
case UPB_DESCRIPTOR_TYPE_DOUBLE:
upb_fielddef_settype(f, UPB_TYPE_DOUBLE);
@@ -948,7 +1121,7 @@ void upb_fielddef_setdescriptortype(upb_fielddef *f, int type) {
case UPB_DESCRIPTOR_TYPE_ENUM:
upb_fielddef_settype(f, UPB_TYPE_ENUM);
break;
- default: assert(false);
+ default: UPB_ASSERT(false);
}
if (type == UPB_DESCRIPTOR_TYPE_FIXED64 ||
@@ -1006,34 +1179,34 @@ upb_descriptortype_t upb_fielddef_descriptortype(const upb_fielddef *f) {
}
void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->is_extension_ = is_extension;
}
void upb_fielddef_setlazy(upb_fielddef *f, bool lazy) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->lazy_ = lazy;
}
void upb_fielddef_setpacked(upb_fielddef *f, bool packed) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->packed_ = packed;
}
void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_checklabel(label));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_checklabel(label));
f->label_ = label;
}
void upb_fielddef_setintfmt(upb_fielddef *f, upb_intfmt_t fmt) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_checkintfmt(fmt));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_checkintfmt(fmt));
f->intfmt = fmt;
}
void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
- assert(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
f->tagdelim = tag_delim;
f->tagdelim = tag_delim;
}
@@ -1041,12 +1214,12 @@ void upb_fielddef_settagdelim(upb_fielddef *f, bool tag_delim) {
static bool checksetdefault(upb_fielddef *f, upb_fieldtype_t type) {
if (!f->type_is_set_ || upb_fielddef_isfrozen(f) ||
upb_fielddef_type(f) != type) {
- assert(false);
+ UPB_ASSERT(false);
return false;
}
if (f->default_is_string) {
str_t *s = f->defaultval.bytes;
- assert(s || type == UPB_TYPE_ENUM);
+ UPB_ASSERT(s || type == UPB_TYPE_ENUM);
if (s) freestr(s);
}
f->default_is_string = false;
@@ -1094,16 +1267,16 @@ void upb_fielddef_setdefaultdouble(upb_fielddef *f, double value) {
bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
upb_status *s) {
str_t *str2;
- assert(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(upb_fielddef_isstring(f) || f->type_ == UPB_TYPE_ENUM);
if (f->type_ == UPB_TYPE_ENUM && !upb_isident(str, len, false, s))
return false;
if (f->default_is_string) {
str_t *s = f->defaultval.bytes;
- assert(s || f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(s || f->type_ == UPB_TYPE_ENUM);
if (s) freestr(s);
} else {
- assert(f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_ == UPB_TYPE_ENUM);
}
str2 = newstr(str, len);
@@ -1114,18 +1287,18 @@ bool upb_fielddef_setdefaultstr(upb_fielddef *f, const void *str, size_t len,
void upb_fielddef_setdefaultcstr(upb_fielddef *f, const char *str,
upb_status *s) {
- assert(f->type_is_set_);
+ UPB_ASSERT(f->type_is_set_);
upb_fielddef_setdefaultstr(f, str, str ? strlen(str) : 0, s);
}
bool upb_fielddef_enumhasdefaultint32(const upb_fielddef *f) {
int32_t val;
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
return enumdefaultint32(f, &val);
}
bool upb_fielddef_enumhasdefaultstr(const upb_fielddef *f) {
- assert(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
+ UPB_ASSERT(f->type_is_set_ && f->type_ == UPB_TYPE_ENUM);
return enumdefaultstr(f) != NULL;
}
@@ -1147,7 +1320,7 @@ static bool upb_subdef_typecheck(upb_fielddef *f, const upb_def *subdef,
static void release_subdef(upb_fielddef *f) {
if (f->subdef_is_symbolic) {
- free(f->sub.name);
+ upb_gfree(f->sub.name);
} else if (f->sub.def) {
upb_unref2(f->sub.def, f);
}
@@ -1155,8 +1328,8 @@ static void release_subdef(upb_fielddef *f) {
bool upb_fielddef_setsubdef(upb_fielddef *f, const upb_def *subdef,
upb_status *s) {
- assert(!upb_fielddef_isfrozen(f));
- assert(upb_fielddef_hassubdef(f));
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
+ UPB_ASSERT(upb_fielddef_hassubdef(f));
if (subdef && !upb_subdef_typecheck(f, subdef, s)) return false;
release_subdef(f);
f->sub.def = subdef;
@@ -1177,15 +1350,23 @@ bool upb_fielddef_setenumsubdef(upb_fielddef *f, const upb_enumdef *subdef,
bool upb_fielddef_setsubdefname(upb_fielddef *f, const char *name,
upb_status *s) {
- assert(!upb_fielddef_isfrozen(f));
+ char *name_copy;
+ UPB_ASSERT(!upb_fielddef_isfrozen(f));
if (!upb_fielddef_hassubdef(f)) {
upb_status_seterrmsg(s, "field type does not accept a subdef");
return false;
}
+
+ name_copy = upb_gstrdup(name);
+ if (!name_copy) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+
/* TODO: validate name (upb_isident() doesn't quite work atm because this name
* may have a leading "."). */
release_subdef(f);
- f->sub.name = upb_strdup(name);
+ f->sub.name = name_copy;
f->subdef_is_symbolic = true;
return true;
}
@@ -1212,6 +1393,16 @@ bool upb_fielddef_ismap(const upb_fielddef *f) {
upb_msgdef_mapentry(upb_fielddef_msgsubdef(f));
}
+bool upb_fielddef_haspresence(const upb_fielddef *f) {
+ if (upb_fielddef_isseq(f)) return false;
+ if (upb_fielddef_issubmsg(f)) return true;
+
+ /* Primitive field: return true unless there is a message that specifies
+ * presence should not exist. */
+ if (f->msg_is_symbolic || !f->msg.def) return true;
+ return f->msg.def->syntax == UPB_SYNTAX_PROTO2;
+}
+
bool upb_fielddef_hassubdef(const upb_fielddef *f) {
return upb_fielddef_issubmsg(f) || upb_fielddef_type(f) == UPB_TYPE_ENUM;
}
@@ -1234,6 +1425,7 @@ static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
void *closure) {
upb_msg_oneof_iter o;
const upb_msgdef *m = (const upb_msgdef*)r;
+ const upb_def *def = upb_msgdef_upcast(m);
upb_msg_field_iter i;
for(upb_msg_field_begin(&i, m);
!upb_msg_field_done(&i);
@@ -1245,37 +1437,42 @@ static void visitmsg(const upb_refcounted *r, upb_refcounted_visit *visit,
!upb_msg_oneof_done(&o);
upb_msg_oneof_next(&o)) {
upb_oneofdef *f = upb_msg_iter_oneof(&o);
- visit(r, upb_oneofdef_upcast2(f), closure);
+ visit(r, upb_oneofdef_upcast(f), closure);
+ }
+ if (upb_def_file(def)) {
+ visit(r, upb_filedef_upcast(upb_def_file(def)), closure);
}
}
static void freemsg(upb_refcounted *r) {
upb_msgdef *m = (upb_msgdef*)r;
- upb_strtable_uninit(&m->ntoo);
upb_strtable_uninit(&m->ntof);
upb_inttable_uninit(&m->itof);
upb_def_uninit(upb_msgdef_upcast_mutable(m));
- free(m);
+ upb_gfree(m);
}
+const struct upb_refcounted_vtbl upb_msgdef_vtbl = {visitmsg, freemsg};
+
upb_msgdef *upb_msgdef_new(const void *owner) {
- static const struct upb_refcounted_vtbl vtbl = {visitmsg, freemsg};
- upb_msgdef *m = malloc(sizeof(*m));
+ upb_msgdef *m = upb_gmalloc(sizeof(*m));
if (!m) return NULL;
- if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &vtbl, owner))
+
+ if (!upb_def_init(upb_msgdef_upcast_mutable(m), UPB_DEF_MSG, &upb_msgdef_vtbl,
+ owner)) {
goto err2;
- if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err3;
- if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err2;
- if (!upb_strtable_init(&m->ntoo, UPB_CTYPE_PTR)) goto err1;
+ }
+
+ if (!upb_inttable_init(&m->itof, UPB_CTYPE_PTR)) goto err2;
+ if (!upb_strtable_init(&m->ntof, UPB_CTYPE_PTR)) goto err1;
m->map_entry = false;
+ m->syntax = UPB_SYNTAX_PROTO2;
return m;
err1:
- upb_strtable_uninit(&m->ntof);
-err2:
upb_inttable_uninit(&m->itof);
-err3:
- free(m);
+err2:
+ upb_gfree(m);
return NULL;
}
@@ -1290,7 +1487,8 @@ upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner) {
upb_def_fullname(upb_msgdef_upcast(m)),
NULL);
newm->map_entry = m->map_entry;
- UPB_ASSERT_VAR(ok, ok);
+ newm->syntax = m->syntax;
+ UPB_ASSERT(ok);
for(upb_msg_field_begin(&i, m);
!upb_msg_field_done(&i);
upb_msg_field_next(&i)) {
@@ -1323,11 +1521,28 @@ const char *upb_msgdef_fullname(const upb_msgdef *m) {
return upb_def_fullname(upb_msgdef_upcast(m));
}
+const char *upb_msgdef_name(const upb_msgdef *m) {
+ return upb_def_name(upb_msgdef_upcast(m));
+}
+
bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname,
upb_status *s) {
return upb_def_setfullname(upb_msgdef_upcast_mutable(m), fullname, s);
}
+bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax) {
+ if (syntax != UPB_SYNTAX_PROTO2 && syntax != UPB_SYNTAX_PROTO3) {
+ return false;
+ }
+
+ m->syntax = syntax;
+ return true;
+}
+
+upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m) {
+ return m->syntax;
+}
+
/* Helper: check that the field |f| is safe to add to msgdef |m|. Set an error
* on status |s| and return false if not. */
static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
@@ -1338,9 +1553,11 @@ static bool check_field_add(const upb_msgdef *m, const upb_fielddef *f,
} else if (upb_fielddef_name(f) == NULL || upb_fielddef_number(f) == 0) {
upb_status_seterrmsg(s, "field name or number were not set");
return false;
- } else if (upb_msgdef_ntofz(m, upb_fielddef_name(f)) ||
- upb_msgdef_itof(m, upb_fielddef_number(f))) {
- upb_status_seterrmsg(s, "duplicate field name or number for field");
+ } else if (upb_msgdef_itof(m, upb_fielddef_number(f))) {
+ upb_status_seterrmsg(s, "duplicate field number");
+ return false;
+ } else if (upb_strtable_lookup(&m->ntof, upb_fielddef_name(f), NULL)) {
+ upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
return false;
}
return true;
@@ -1373,6 +1590,7 @@ bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
* This method is idempotent. Check if |f| is already part of this msgdef and
* return immediately if so. */
if (upb_fielddef_containingtype(f) == m) {
+ if (ref_donor) upb_fielddef_unref(f, ref_donor);
return true;
}
@@ -1401,8 +1619,8 @@ bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
} else if (upb_oneofdef_name(o) == NULL) {
upb_status_seterrmsg(s, "oneofdef name was not set");
return false;
- } else if (upb_msgdef_ntooz(m, upb_oneofdef_name(o))) {
- upb_status_seterrmsg(s, "duplicate oneof name");
+ } else if (upb_strtable_lookup(&m->ntof, upb_oneofdef_name(o), NULL)) {
+ upb_status_seterrmsg(s, "name conflicts with existing field or oneof");
return false;
}
@@ -1419,7 +1637,7 @@ bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
/* Add oneof itself first. */
o->parent = m;
- upb_strtable_insert(&m->ntoo, upb_oneofdef_name(o), upb_value_ptr(o));
+ upb_strtable_insert(&m->ntof, upb_oneofdef_name(o), upb_value_ptr(o));
upb_ref2(o, m);
upb_ref2(m, o);
@@ -1443,27 +1661,51 @@ const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) {
const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name,
size_t len) {
upb_value val;
- return upb_strtable_lookup2(&m->ntof, name, len, &val) ?
- upb_value_getptr(val) : NULL;
+
+ if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
+ return NULL;
+ }
+
+ return upb_trygetfield(upb_value_getptr(val));
}
const upb_oneofdef *upb_msgdef_ntoo(const upb_msgdef *m, const char *name,
size_t len) {
upb_value val;
- return upb_strtable_lookup2(&m->ntoo, name, len, &val) ?
- upb_value_getptr(val) : NULL;
+
+ if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
+ return NULL;
+ }
+
+ return upb_trygetoneof(upb_value_getptr(val));
+}
+
+bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
+ const upb_fielddef **f, const upb_oneofdef **o) {
+ upb_value val;
+
+ if (!upb_strtable_lookup2(&m->ntof, name, len, &val)) {
+ return false;
+ }
+
+ *o = upb_trygetoneof(upb_value_getptr(val));
+ *f = upb_trygetfield(upb_value_getptr(val));
+ UPB_ASSERT((*o != NULL) ^ (*f != NULL)); /* Exactly one of the two should be set. */
+ return true;
}
int upb_msgdef_numfields(const upb_msgdef *m) {
- return upb_strtable_count(&m->ntof);
+ /* The number table contains only fields. */
+ return upb_inttable_count(&m->itof);
}
int upb_msgdef_numoneofs(const upb_msgdef *m) {
- return upb_strtable_count(&m->ntoo);
+ /* The name table includes oneofs, and the number table does not. */
+ return upb_strtable_count(&m->ntof) - upb_inttable_count(&m->itof);
}
void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry) {
- assert(!upb_msgdef_isfrozen(m));
+ UPB_ASSERT(!upb_msgdef_isfrozen(m));
m->map_entry = map_entry;
}
@@ -1490,10 +1732,21 @@ void upb_msg_field_iter_setdone(upb_msg_field_iter *iter) {
}
void upb_msg_oneof_begin(upb_msg_oneof_iter *iter, const upb_msgdef *m) {
- upb_strtable_begin(iter, &m->ntoo);
+ upb_strtable_begin(iter, &m->ntof);
+ /* We need to skip past any initial fields. */
+ while (!upb_strtable_done(iter) &&
+ !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter)))) {
+ upb_strtable_next(iter);
+ }
}
-void upb_msg_oneof_next(upb_msg_oneof_iter *iter) { upb_strtable_next(iter); }
+void upb_msg_oneof_next(upb_msg_oneof_iter *iter) {
+ /* We need to skip past fields to return only oneofs. */
+ do {
+ upb_strtable_next(iter);
+ } while (!upb_strtable_done(iter) &&
+ !upb_isoneof(upb_value_getptr(upb_strtable_iter_value(iter))));
+}
bool upb_msg_oneof_done(const upb_msg_oneof_iter *iter) {
return upb_strtable_done(iter);
@@ -1526,26 +1779,36 @@ static void freeoneof(upb_refcounted *r) {
upb_oneofdef *o = (upb_oneofdef*)r;
upb_strtable_uninit(&o->ntof);
upb_inttable_uninit(&o->itof);
- upb_def_uninit(upb_oneofdef_upcast_mutable(o));
- free(o);
+ upb_gfree((void*)o->name);
+ upb_gfree(o);
}
+const struct upb_refcounted_vtbl upb_oneofdef_vtbl = {visitoneof, freeoneof};
+
upb_oneofdef *upb_oneofdef_new(const void *owner) {
- static const struct upb_refcounted_vtbl vtbl = {visitoneof, freeoneof};
- upb_oneofdef *o = malloc(sizeof(*o));
+ upb_oneofdef *o = upb_gmalloc(sizeof(*o));
+
+ if (!o) {
+ return NULL;
+ }
+
o->parent = NULL;
- if (!o) return NULL;
- if (!upb_def_init(upb_oneofdef_upcast_mutable(o), UPB_DEF_ONEOF, &vtbl,
- owner))
+ o->name = NULL;
+
+ if (!upb_refcounted_init(upb_oneofdef_upcast_mutable(o), &upb_oneofdef_vtbl,
+ owner)) {
goto err2;
+ }
+
if (!upb_inttable_init(&o->itof, UPB_CTYPE_PTR)) goto err2;
if (!upb_strtable_init(&o->ntof, UPB_CTYPE_PTR)) goto err1;
+
return o;
err1:
upb_inttable_uninit(&o->itof);
err2:
- free(o);
+ upb_gfree(o);
return NULL;
}
@@ -1554,9 +1817,8 @@ upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
upb_oneof_iter i;
upb_oneofdef *newo = upb_oneofdef_new(owner);
if (!newo) return NULL;
- ok = upb_def_setfullname(upb_oneofdef_upcast_mutable(newo),
- upb_def_fullname(upb_oneofdef_upcast(o)), NULL);
- UPB_ASSERT_VAR(ok, ok);
+ ok = upb_oneofdef_setname(newo, upb_oneofdef_name(o), NULL);
+ UPB_ASSERT(ok);
for (upb_oneof_begin(&i, o); !upb_oneof_done(&i); upb_oneof_next(&i)) {
upb_fielddef *f = upb_fielddef_dup(upb_oneof_iter_field(&i), &f);
if (!f || !upb_oneofdef_addfield(newo, f, &f, NULL)) {
@@ -1567,17 +1829,28 @@ upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner) {
return newo;
}
-const char *upb_oneofdef_name(const upb_oneofdef *o) {
- return upb_def_fullname(upb_oneofdef_upcast(o));
-}
+const char *upb_oneofdef_name(const upb_oneofdef *o) { return o->name; }
-bool upb_oneofdef_setname(upb_oneofdef *o, const char *fullname,
- upb_status *s) {
+bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s) {
+ UPB_ASSERT(!upb_oneofdef_isfrozen(o));
if (upb_oneofdef_containingtype(o)) {
upb_status_seterrmsg(s, "oneof already added to a message");
return false;
}
- return upb_def_setfullname(upb_oneofdef_upcast_mutable(o), fullname, s);
+
+ if (!upb_isident(name, strlen(name), true, s)) {
+ return false;
+ }
+
+ name = upb_gstrdup(name);
+ if (!name) {
+ upb_status_seterrmsg(s, "One of memory");
+ return false;
+ }
+
+ upb_gfree((void*)o->name);
+ o->name = name;
+ return true;
}
const upb_msgdef *upb_oneofdef_containingtype(const upb_oneofdef *o) {
@@ -1591,8 +1864,8 @@ int upb_oneofdef_numfields(const upb_oneofdef *o) {
bool upb_oneofdef_addfield(upb_oneofdef *o, upb_fielddef *f,
const void *ref_donor,
upb_status *s) {
- assert(!upb_oneofdef_isfrozen(o));
- assert(!o->parent || !upb_msgdef_isfrozen(o->parent));
+ UPB_ASSERT(!upb_oneofdef_isfrozen(o));
+ UPB_ASSERT(!o->parent || !upb_msgdef_isfrozen(o->parent));
/* This method is idempotent. Check if |f| is already part of this oneofdef
* and return immediately if so. */
@@ -1696,287 +1969,209 @@ void upb_oneof_iter_setdone(upb_oneof_iter *iter) {
upb_inttable_iter_setdone(iter);
}
+/* upb_filedef ****************************************************************/
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-typedef struct cleanup_ent {
- upb_cleanup_func *cleanup;
- void *ud;
- struct cleanup_ent *next;
-} cleanup_ent;
-
-static void *seeded_alloc(void *ud, void *ptr, size_t oldsize, size_t size);
-
-/* Default allocator **********************************************************/
-
-/* Just use realloc, keeping all allocated blocks in a linked list to destroy at
- * the end. */
-
-typedef struct mem_block {
- /* List is doubly-linked, because in cases where realloc() moves an existing
- * block, we need to be able to remove the old pointer from the list
- * efficiently. */
- struct mem_block *prev, *next;
-#ifndef NDEBUG
- size_t size; /* Doesn't include mem_block structure. */
-#endif
-} mem_block;
-
-typedef struct {
- mem_block *head;
-} default_alloc_ud;
-
-static void *default_alloc(void *_ud, void *ptr, size_t oldsize, size_t size) {
- default_alloc_ud *ud = _ud;
- mem_block *from, *block;
- void *ret;
- UPB_UNUSED(oldsize);
-
- from = ptr ? (void*)((char*)ptr - sizeof(mem_block)) : NULL;
-
-#ifndef NDEBUG
- if (from) {
- assert(oldsize <= from->size);
- }
-#endif
-
- /* TODO(haberman): we probably need to provide even better alignment here,
- * like 16-byte alignment of the returned data pointer. */
- block = realloc(from, size + sizeof(mem_block));
- if (!block) return NULL;
- ret = (char*)block + sizeof(*block);
-
-#ifndef NDEBUG
- block->size = size;
-#endif
+static void visitfiledef(const upb_refcounted *r, upb_refcounted_visit *visit,
+ void *closure) {
+ const upb_filedef *f = (const upb_filedef*)r;
+ size_t i;
- if (from) {
- if (block != from) {
- /* The block was moved, so pointers in next and prev blocks must be
- * updated to its new location. */
- if (block->next) block->next->prev = block;
- if (block->prev) block->prev->next = block;
- if (ud->head == from) ud->head = block;
- }
- } else {
- /* Insert at head of linked list. */
- block->prev = NULL;
- block->next = ud->head;
- if (block->next) block->next->prev = block;
- ud->head = block;
+ for(i = 0; i < upb_filedef_defcount(f); i++) {
+ visit(r, upb_def_upcast(upb_filedef_def(f, i)), closure);
}
-
- return ret;
}
-static void default_alloc_cleanup(void *_ud) {
- default_alloc_ud *ud = _ud;
- mem_block *block = ud->head;
+static void freefiledef(upb_refcounted *r) {
+ upb_filedef *f = (upb_filedef*)r;
+ size_t i;
- while (block) {
- void *to_free = block;
- block = block->next;
- free(to_free);
+ for(i = 0; i < upb_filedef_depcount(f); i++) {
+ upb_filedef_unref(upb_filedef_dep(f, i), f);
}
+
+ upb_inttable_uninit(&f->defs);
+ upb_inttable_uninit(&f->deps);
+ upb_gfree((void*)f->name);
+ upb_gfree((void*)f->package);
+ upb_gfree(f);
}
+const struct upb_refcounted_vtbl upb_filedef_vtbl = {visitfiledef, freefiledef};
-/* Standard error functions ***************************************************/
+upb_filedef *upb_filedef_new(const void *owner) {
+ upb_filedef *f = upb_gmalloc(sizeof(*f));
-static bool default_err(void *ud, const upb_status *status) {
- UPB_UNUSED(ud);
- UPB_UNUSED(status);
- return false;
-}
-
-static bool write_err_to(void *ud, const upb_status *status) {
- upb_status *copy_to = ud;
- upb_status_copy(copy_to, status);
- return false;
-}
+ if (!f) {
+ return NULL;
+ }
+ f->package = NULL;
+ f->name = NULL;
+ f->syntax = UPB_SYNTAX_PROTO2;
-/* upb_env ********************************************************************/
+ if (!upb_refcounted_init(upb_filedef_upcast_mutable(f), &upb_filedef_vtbl,
+ owner)) {
+ goto err;
+ }
-void upb_env_init(upb_env *e) {
- default_alloc_ud *ud = (default_alloc_ud*)&e->default_alloc_ud;
- e->ok_ = true;
- e->bytes_allocated = 0;
- e->cleanup_head = NULL;
+ if (!upb_inttable_init(&f->defs, UPB_CTYPE_CONSTPTR)) {
+ goto err;
+ }
- ud->head = NULL;
+ if (!upb_inttable_init(&f->deps, UPB_CTYPE_CONSTPTR)) {
+ goto err2;
+ }
- /* Set default functions. */
- upb_env_setallocfunc(e, default_alloc, ud);
- upb_env_seterrorfunc(e, default_err, NULL);
-}
+ return f;
-void upb_env_uninit(upb_env *e) {
- cleanup_ent *ent = e->cleanup_head;
- while (ent) {
- ent->cleanup(ent->ud);
- ent = ent->next;
- }
+err2:
+ upb_inttable_uninit(&f->defs);
- /* Must do this after running cleanup functions, because this will delete
- the memory we store our cleanup entries in! */
- if (e->alloc == default_alloc) {
- default_alloc_cleanup(e->alloc_ud);
- }
+err:
+ upb_gfree(f);
+ return NULL;
}
-UPB_FORCEINLINE void upb_env_setallocfunc(upb_env *e, upb_alloc_func *alloc,
- void *ud) {
- e->alloc = alloc;
- e->alloc_ud = ud;
+const char *upb_filedef_name(const upb_filedef *f) {
+ return f->name;
}
-UPB_FORCEINLINE void upb_env_seterrorfunc(upb_env *e, upb_error_func *func,
- void *ud) {
- e->err = func;
- e->err_ud = ud;
+const char *upb_filedef_package(const upb_filedef *f) {
+ return f->package;
}
-void upb_env_reporterrorsto(upb_env *e, upb_status *status) {
- e->err = write_err_to;
- e->err_ud = status;
+upb_syntax_t upb_filedef_syntax(const upb_filedef *f) {
+ return f->syntax;
}
-bool upb_env_ok(const upb_env *e) {
- return e->ok_;
+size_t upb_filedef_defcount(const upb_filedef *f) {
+ return upb_inttable_count(&f->defs);
}
-bool upb_env_reporterror(upb_env *e, const upb_status *status) {
- e->ok_ = false;
- return e->err(e->err_ud, status);
+size_t upb_filedef_depcount(const upb_filedef *f) {
+ return upb_inttable_count(&f->deps);
}
-bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
- cleanup_ent *ent = upb_env_malloc(e, sizeof(cleanup_ent));
- if (!ent) return false;
-
- ent->cleanup = func;
- ent->ud = ud;
- ent->next = e->cleanup_head;
- e->cleanup_head = ent;
-
- return true;
-}
+const upb_def *upb_filedef_def(const upb_filedef *f, size_t i) {
+ upb_value v;
-void *upb_env_malloc(upb_env *e, size_t size) {
- e->bytes_allocated += size;
- if (e->alloc == seeded_alloc) {
- /* This is equivalent to the next branch, but allows inlining for a
- * measurable perf benefit. */
- return seeded_alloc(e->alloc_ud, NULL, 0, size);
+ if (upb_inttable_lookup32(&f->defs, i, &v)) {
+ return upb_value_getconstptr(v);
} else {
- return e->alloc(e->alloc_ud, NULL, 0, size);
+ return NULL;
}
}
-void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
- char *ret;
- assert(oldsize <= size);
- ret = e->alloc(e->alloc_ud, ptr, oldsize, size);
-
-#ifndef NDEBUG
- /* Overwrite non-preserved memory to ensure callers are passing the oldsize
- * that they truly require. */
- memset(ret + oldsize, 0xff, size - oldsize);
-#endif
+const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i) {
+ upb_value v;
- return ret;
+ if (upb_inttable_lookup32(&f->deps, i, &v)) {
+ return upb_value_getconstptr(v);
+ } else {
+ return NULL;
+ }
}
-size_t upb_env_bytesallocated(const upb_env *e) {
- return e->bytes_allocated;
+bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s) {
+ name = upb_gstrdup(name);
+ if (!name) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+ upb_gfree((void*)f->name);
+ f->name = name;
+ return true;
}
-
-/* upb_seededalloc ************************************************************/
-
-/* Be conservative and choose 16 in case anyone is using SSE. */
-static const size_t maxalign = 16;
-
-static size_t align_up(size_t size) {
- return ((size + maxalign - 1) / maxalign) * maxalign;
+bool upb_filedef_setpackage(upb_filedef *f, const char *package,
+ upb_status *s) {
+ if (!upb_isident(package, strlen(package), true, s)) return false;
+ package = upb_gstrdup(package);
+ if (!package) {
+ upb_upberr_setoom(s);
+ return false;
+ }
+ upb_gfree((void*)f->package);
+ f->package = package;
+ return true;
}
-UPB_FORCEINLINE static void *seeded_alloc(void *ud, void *ptr, size_t oldsize,
- size_t size) {
- upb_seededalloc *a = ud;
-
- size = align_up(size);
-
- assert(a->mem_limit >= a->mem_ptr);
+bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax,
+ upb_status *s) {
+ UPB_UNUSED(s);
+ if (syntax != UPB_SYNTAX_PROTO2 &&
+ syntax != UPB_SYNTAX_PROTO3) {
+ upb_status_seterrmsg(s, "Unknown syntax value.");
+ return false;
+ }
+ f->syntax = syntax;
- if (oldsize == 0 && size <= (size_t)(a->mem_limit - a->mem_ptr)) {
- /* Fast path: we can satisfy from the initial allocation. */
- void *ret = a->mem_ptr;
- a->mem_ptr += size;
- return ret;
- } else {
- char *chptr = ptr;
- /* Slow path: fallback to other allocator. */
- a->need_cleanup = true;
- /* Is `ptr` part of the user-provided initial block? Don't pass it to the
- * default allocator if so; otherwise, it may try to realloc() the block. */
- if (chptr >= a->mem_base && chptr < a->mem_limit) {
- void *ret;
- assert(chptr + oldsize <= a->mem_limit);
- ret = a->alloc(a->alloc_ud, NULL, 0, size);
- if (ret) memcpy(ret, ptr, oldsize);
- return ret;
- } else {
- return a->alloc(a->alloc_ud, ptr, oldsize, size);
+ {
+ /* Set all messages in this file to match. */
+ size_t i;
+ for (i = 0; i < upb_filedef_defcount(f); i++) {
+ /* Casting const away is safe since all defs in mutable filedef must
+ * also be mutable. */
+ upb_def *def = (upb_def*)upb_filedef_def(f, i);
+
+ upb_msgdef *m = upb_dyncast_msgdef_mutable(def);
+ if (m) {
+ m->syntax = syntax;
+ }
}
}
-}
-
-void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len) {
- default_alloc_ud *ud = (default_alloc_ud*)&a->default_alloc_ud;
- a->mem_base = mem;
- a->mem_ptr = mem;
- a->mem_limit = (char*)mem + len;
- a->need_cleanup = false;
- a->returned_allocfunc = false;
-
- ud->head = NULL;
- upb_seededalloc_setfallbackalloc(a, default_alloc, ud);
+ return true;
}
-void upb_seededalloc_uninit(upb_seededalloc *a) {
- if (a->alloc == default_alloc && a->need_cleanup) {
- default_alloc_cleanup(a->alloc_ud);
+bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
+ upb_status *s) {
+ if (def->file) {
+ upb_status_seterrmsg(s, "Def is already part of another filedef.");
+ return false;
}
-}
-UPB_FORCEINLINE void upb_seededalloc_setfallbackalloc(upb_seededalloc *a,
- upb_alloc_func *alloc,
- void *ud) {
- assert(!a->returned_allocfunc);
- a->alloc = alloc;
- a->alloc_ud = ud;
+ if (upb_inttable_push(&f->defs, upb_value_constptr(def))) {
+ def->file = f;
+ upb_ref2(def, f);
+ upb_ref2(f, def);
+ if (ref_donor) upb_def_unref(def, ref_donor);
+ if (def->type == UPB_DEF_MSG) {
+ upb_downcast_msgdef_mutable(def)->syntax = f->syntax;
+ }
+ return true;
+ } else {
+ upb_upberr_setoom(s);
+ return false;
+ }
}
-upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a) {
- a->returned_allocfunc = true;
- return seeded_alloc;
+bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep) {
+ if (upb_inttable_push(&f->deps, upb_value_constptr(dep))) {
+ /* Regular ref instead of ref2 because files can't form cycles. */
+ upb_filedef_ref(dep, f);
+ return true;
+ } else {
+ return false;
+ }
}
/*
** TODO(haberman): it's unclear whether a lot of the consistency checks should
-** assert() or return false.
+** UPB_ASSERT() or return false.
*/
-#include <stdlib.h>
#include <string.h>
+static void *upb_calloc(size_t size) {
+ void *mem = upb_gmalloc(size);
+ if (mem) {
+ memset(mem, 0, size);
+ }
+ return mem;
+}
/* Defined for the sole purpose of having a unique pointer value for
* UPB_NO_CLOSURE. */
@@ -1996,8 +2191,8 @@ static void freehandlers(upb_refcounted *r) {
upb_inttable_uninit(&h->cleanup_);
upb_msgdef_unref(h->msg, h);
- free(h->sub);
- free(h);
+ upb_gfree(h->sub);
+ upb_gfree(h);
}
static void visithandlers(const upb_refcounted *r, upb_refcounted_visit *visit,
@@ -2073,7 +2268,7 @@ oom:
static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
upb_handlertype_t type) {
upb_selector_t sel;
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
if (upb_handlers_msgdef(h) != upb_fielddef_containingtype(f)) {
upb_status_seterrf(
&h->status_, "type mismatch: field %s does not belong to message %s",
@@ -2093,7 +2288,7 @@ static int32_t trygetsel(upb_handlers *h, const upb_fielddef *f,
static upb_selector_t handlers_getsel(upb_handlers *h, const upb_fielddef *f,
upb_handlertype_t type) {
int32_t sel = trygetsel(h, f, type);
- assert(sel >= 0);
+ UPB_ASSERT(sel >= 0);
return sel;
}
@@ -2109,7 +2304,7 @@ static bool doset(upb_handlers *h, int32_t sel, const upb_fielddef *f,
const void *closure_type;
const void **context_closure_type;
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
if (sel < 0) {
upb_status_seterrmsg(&h->status_,
@@ -2189,7 +2384,7 @@ const void *effective_closure_type(upb_handlers *h, const upb_fielddef *f,
const void *ret;
upb_selector_t sel;
- assert(type != UPB_HANDLER_STRING);
+ UPB_ASSERT(type != UPB_HANDLER_STRING);
ret = h->top_closure_type;
if (upb_fielddef_isseq(f) &&
@@ -2244,17 +2439,23 @@ upb_handlers *upb_handlers_new(const upb_msgdef *md, const void *owner) {
int extra;
upb_handlers *h;
- assert(upb_msgdef_isfrozen(md));
+ UPB_ASSERT(upb_msgdef_isfrozen(md));
extra = sizeof(upb_handlers_tabent) * (md->selector_count - 1);
- h = calloc(sizeof(*h) + extra, 1);
+ h = upb_calloc(sizeof(*h) + extra);
if (!h) return NULL;
h->msg = md;
upb_msgdef_ref(h->msg, h);
upb_status_clear(&h->status_);
- h->sub = calloc(md->submsg_field_count, sizeof(*h->sub));
- if (!h->sub) goto oom;
+
+ if (md->submsg_field_count > 0) {
+ h->sub = upb_calloc(md->submsg_field_count * sizeof(*h->sub));
+ if (!h->sub) goto oom;
+ } else {
+ h->sub = 0;
+ }
+
if (!upb_refcounted_init(upb_handlers_upcast_mutable(h), &vtbl, owner))
goto oom;
if (!upb_inttable_init(&h->cleanup_, UPB_CTYPE_FPTR)) goto oom;
@@ -2287,18 +2488,18 @@ const upb_handlers *upb_handlers_newfrozen(const upb_msgdef *m,
r = upb_handlers_upcast_mutable(ret);
ok = upb_refcounted_freeze(&r, 1, NULL, UPB_MAX_HANDLER_DEPTH);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return ret;
}
const upb_status *upb_handlers_status(upb_handlers *h) {
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
return &h->status_;
}
void upb_handlers_clearerr(upb_handlers *h) {
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
upb_status_clear(&h->status_);
}
@@ -2334,16 +2535,16 @@ bool upb_handlers_setstartmsg(upb_handlers *h, upb_startmsg_handlerfunc *func,
bool upb_handlers_setendmsg(upb_handlers *h, upb_endmsg_handlerfunc *func,
upb_handlerattr *attr) {
- assert(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
return doset(h, UPB_ENDMSG_SELECTOR, NULL, UPB_HANDLER_INT32,
(upb_func *)func, attr);
}
bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
const upb_handlers *sub) {
- assert(sub);
- assert(!upb_handlers_isfrozen(h));
- assert(upb_fielddef_issubmsg(f));
+ UPB_ASSERT(sub);
+ UPB_ASSERT(!upb_handlers_isfrozen(h));
+ UPB_ASSERT(upb_fielddef_issubmsg(f));
if (SUBH_F(h, f)) return false; /* Can't reset. */
if (upb_msgdef_upcast(upb_handlers_msgdef(sub)) != upb_fielddef_subdef(f)) {
return false;
@@ -2355,7 +2556,7 @@ bool upb_handlers_setsubhandlers(upb_handlers *h, const upb_fielddef *f,
const upb_handlers *upb_handlers_getsubhandlers(const upb_handlers *h,
const upb_fielddef *f) {
- assert(upb_fielddef_issubmsg(f));
+ UPB_ASSERT(upb_fielddef_issubmsg(f));
return SUBH_F(h, f);
}
@@ -2381,7 +2582,7 @@ bool upb_handlers_addcleanup(upb_handlers *h, void *p, upb_handlerfree *func) {
return false;
}
ok = upb_inttable_insertptr(&h->cleanup_, p, upb_value_fptr(func));
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return true;
}
@@ -2482,7 +2683,7 @@ upb_handlertype_t upb_handlers_getprimitivehandlertype(const upb_fielddef *f) {
case UPB_TYPE_FLOAT: return UPB_HANDLER_FLOAT;
case UPB_TYPE_DOUBLE: return UPB_HANDLER_DOUBLE;
case UPB_TYPE_BOOL: return UPB_HANDLER_BOOL;
- default: assert(false); return -1; /* Invalid input. */
+ default: UPB_ASSERT(false); return -1; /* Invalid input. */
}
}
@@ -2545,7 +2746,7 @@ bool upb_handlers_getselector(const upb_fielddef *f, upb_handlertype_t type,
*s = f->selector_base;
break;
}
- assert((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
+ UPB_ASSERT((size_t)*s < upb_fielddef_containingtype(f)->selector_count);
return true;
}
@@ -2669,7 +2870,6 @@ bool upb_byteshandler_setendstr(upb_byteshandler *h,
#include <setjmp.h>
-#include <stdlib.h>
static void freeobj(upb_refcounted *o);
@@ -2745,8 +2945,31 @@ void upb_unlock();
/* UPB_DEBUG_REFS mode counts on being able to malloc() memory in some
* code-paths that can normally never fail, like upb_refcounted_ref(). Since
* we have no way to propagage out-of-memory errors back to the user, and since
- * these errors can only occur in UPB_DEBUG_REFS mode, we immediately fail. */
-#define CHECK_OOM(predicate) if (!(predicate)) { assert(predicate); exit(1); }
+ * these errors can only occur in UPB_DEBUG_REFS mode, we use an allocator that
+ * immediately aborts on failure (avoiding the global allocator, which might
+ * inject failures). */
+
+#include <stdlib.h>
+
+static void *upb_debugrefs_allocfunc(upb_alloc *alloc, void *ptr,
+ size_t oldsize, size_t size) {
+ UPB_UNUSED(alloc);
+ UPB_UNUSED(oldsize);
+ if (size == 0) {
+ free(ptr);
+ return NULL;
+ } else {
+ void *ret = realloc(ptr, size);
+
+ if (!ret) {
+ abort();
+ }
+
+ return ret;
+ }
+}
+
+upb_alloc upb_alloc_debugrefs = {&upb_debugrefs_allocfunc};
typedef struct {
int count; /* How many refs there are (duplicates only allowed for ref2). */
@@ -2754,8 +2977,7 @@ typedef struct {
} trackedref;
static trackedref *trackedref_new(bool is_ref2) {
- trackedref *ret = malloc(sizeof(*ret));
- CHECK_OOM(ret);
+ trackedref *ret = upb_malloc(&upb_alloc_debugrefs, sizeof(*ret));
ret->count = 1;
ret->is_ref2 = is_ref2;
return ret;
@@ -2764,7 +2986,7 @@ static trackedref *trackedref_new(bool is_ref2) {
static void track(const upb_refcounted *r, const void *owner, bool ref2) {
upb_value v;
- assert(owner);
+ UPB_ASSERT(owner);
if (owner == UPB_UNTRACKED_REF) return;
upb_lock();
@@ -2775,20 +2997,20 @@ static void track(const upb_refcounted *r, const void *owner, bool ref2) {
* tracking behavior we get with regular refs. Since ref2s only happen
* inside upb, we'll accept this limitation until/unless there is a really
* difficult upb-internal bug that can't be figured out without it. */
- assert(ref2);
- assert(ref->is_ref2);
+ UPB_ASSERT(ref2);
+ UPB_ASSERT(ref->is_ref2);
ref->count++;
} else {
trackedref *ref = trackedref_new(ref2);
- bool ok = upb_inttable_insertptr(r->refs, owner, upb_value_ptr(ref));
- CHECK_OOM(ok);
+ upb_inttable_insertptr2(r->refs, owner, upb_value_ptr(ref),
+ &upb_alloc_debugrefs);
if (ref2) {
/* We know this cast is safe when it is a ref2, because it's coming from
* another refcounted object. */
const upb_refcounted *from = owner;
- assert(!upb_inttable_lookupptr(from->ref2s, r, NULL));
- ok = upb_inttable_insertptr(from->ref2s, r, upb_value_ptr(NULL));
- CHECK_OOM(ok);
+ UPB_ASSERT(!upb_inttable_lookupptr(from->ref2s, r, NULL));
+ upb_inttable_insertptr2(from->ref2s, r, upb_value_ptr(NULL),
+ &upb_alloc_debugrefs);
}
}
upb_unlock();
@@ -2799,15 +3021,15 @@ static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
bool found;
trackedref *ref;
- assert(owner);
+ UPB_ASSERT(owner);
if (owner == UPB_UNTRACKED_REF) return;
upb_lock();
found = upb_inttable_lookupptr(r->refs, owner, &v);
/* This assert will fail if an owner attempts to release a ref it didn't have. */
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
ref = upb_value_getptr(v);
- assert(ref->is_ref2 == ref2);
+ UPB_ASSERT(ref->is_ref2 == ref2);
if (--ref->count == 0) {
free(ref);
upb_inttable_removeptr(r->refs, owner, NULL);
@@ -2816,7 +3038,7 @@ static void untrack(const upb_refcounted *r, const void *owner, bool ref2) {
* another refcounted object. */
const upb_refcounted *from = owner;
bool removed = upb_inttable_removeptr(from->ref2s, r, NULL);
- assert(removed);
+ UPB_ASSERT(removed);
}
}
upb_unlock();
@@ -2829,9 +3051,9 @@ static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
upb_lock();
found = upb_inttable_lookupptr(r->refs, owner, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
ref = upb_value_getptr(v);
- assert(ref->is_ref2 == ref2);
+ UPB_ASSERT(ref->is_ref2 == ref2);
upb_unlock();
}
@@ -2846,19 +3068,17 @@ static void getref2s(const upb_refcounted *owner, upb_inttable *tab) {
upb_value v;
upb_value count;
trackedref *ref;
- bool ok;
bool found;
upb_refcounted *to = (upb_refcounted*)upb_inttable_iter_key(&i);
/* To get the count we need to look in the target's table. */
found = upb_inttable_lookupptr(to->refs, owner, &v);
- assert(found);
+ UPB_ASSERT(found);
ref = upb_value_getptr(v);
count = upb_value_int32(ref->count);
- ok = upb_inttable_insertptr(tab, to, count);
- CHECK_OOM(ok);
+ upb_inttable_insertptr2(tab, to, count, &upb_alloc_debugrefs);
}
upb_unlock();
}
@@ -2876,62 +3096,50 @@ static void visit_check(const upb_refcounted *obj, const upb_refcounted *subobj,
bool removed;
int32_t newcount;
- assert(obj == s->obj);
- assert(subobj);
+ UPB_ASSERT(obj == s->obj);
+ UPB_ASSERT(subobj);
removed = upb_inttable_removeptr(ref2, subobj, &v);
/* The following assertion will fail if the visit() function visits a subobj
* that it did not have a ref2 on, or visits the same subobj too many times. */
- assert(removed);
+ UPB_ASSERT(removed);
newcount = upb_value_getint32(v) - 1;
if (newcount > 0) {
- upb_inttable_insert(ref2, (uintptr_t)subobj, upb_value_int32(newcount));
+ upb_inttable_insert2(ref2, (uintptr_t)subobj, upb_value_int32(newcount),
+ &upb_alloc_debugrefs);
}
}
static void visit(const upb_refcounted *r, upb_refcounted_visit *v,
void *closure) {
- bool ok;
-
/* In DEBUG_REFS mode we know what existing ref2 refs there are, so we know
* exactly the set of nodes that visit() should visit. So we verify visit()'s
* correctness here. */
check_state state;
state.obj = r;
- ok = upb_inttable_init(&state.ref2, UPB_CTYPE_INT32);
- CHECK_OOM(ok);
+ upb_inttable_init2(&state.ref2, UPB_CTYPE_INT32, &upb_alloc_debugrefs);
getref2s(r, &state.ref2);
/* This should visit any children in the ref2 table. */
if (r->vtbl->visit) r->vtbl->visit(r, visit_check, &state);
/* This assertion will fail if the visit() function missed any children. */
- assert(upb_inttable_count(&state.ref2) == 0);
- upb_inttable_uninit(&state.ref2);
+ UPB_ASSERT(upb_inttable_count(&state.ref2) == 0);
+ upb_inttable_uninit2(&state.ref2, &upb_alloc_debugrefs);
if (r->vtbl->visit) r->vtbl->visit(r, v, closure);
}
-static bool trackinit(upb_refcounted *r) {
- r->refs = malloc(sizeof(*r->refs));
- r->ref2s = malloc(sizeof(*r->ref2s));
- if (!r->refs || !r->ref2s) goto err1;
-
- if (!upb_inttable_init(r->refs, UPB_CTYPE_PTR)) goto err1;
- if (!upb_inttable_init(r->ref2s, UPB_CTYPE_PTR)) goto err2;
- return true;
-
-err2:
- upb_inttable_uninit(r->refs);
-err1:
- free(r->refs);
- free(r->ref2s);
- return false;
+static void trackinit(upb_refcounted *r) {
+ r->refs = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->refs));
+ r->ref2s = upb_malloc(&upb_alloc_debugrefs, sizeof(*r->ref2s));
+ upb_inttable_init2(r->refs, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
+ upb_inttable_init2(r->ref2s, UPB_CTYPE_PTR, &upb_alloc_debugrefs);
}
static void trackfree(const upb_refcounted *r) {
- upb_inttable_uninit(r->refs);
- upb_inttable_uninit(r->ref2s);
- free(r->refs);
- free(r->ref2s);
+ upb_inttable_uninit2(r->refs, &upb_alloc_debugrefs);
+ upb_inttable_uninit2(r->ref2s, &upb_alloc_debugrefs);
+ upb_free(&upb_alloc_debugrefs, r->refs);
+ upb_free(&upb_alloc_debugrefs, r->ref2s);
}
#else
@@ -2954,9 +3162,8 @@ static void checkref(const upb_refcounted *r, const void *owner, bool ref2) {
UPB_UNUSED(ref2);
}
-static bool trackinit(upb_refcounted *r) {
+static void trackinit(upb_refcounted *r) {
UPB_UNUSED(r);
- return true;
}
static void trackfree(const upb_refcounted *r) {
@@ -3023,7 +3230,7 @@ static uint64_t trygetattr(const tarjan *t, const upb_refcounted *r) {
static uint64_t getattr(const tarjan *t, const upb_refcounted *r) {
upb_value v;
bool found = upb_inttable_lookupptr(&t->objattr, r, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
return upb_value_getuint64(v);
}
@@ -3037,13 +3244,13 @@ static color_t color(tarjan *t, const upb_refcounted *r) {
}
static void set_gray(tarjan *t, const upb_refcounted *r) {
- assert(color(t, r) == BLACK);
+ UPB_ASSERT(color(t, r) == BLACK);
setattr(t, r, GRAY);
}
/* Pushes an obj onto the Tarjan stack and sets it to GREEN. */
static void push(tarjan *t, const upb_refcounted *r) {
- assert(color(t, r) == BLACK || color(t, r) == GRAY);
+ UPB_ASSERT(color(t, r) == BLACK || color(t, r) == GRAY);
/* This defines the attr layout for the GREEN state. "index" and "lowlink"
* get 31 bits, which is plenty (limit of 2B objects frozen at a time). */
setattr(t, r, GREEN | (t->index << 2) | (t->index << 33));
@@ -3058,7 +3265,7 @@ static void push(tarjan *t, const upb_refcounted *r) {
* SCC group. */
static upb_refcounted *pop(tarjan *t) {
upb_refcounted *r = upb_value_getptr(upb_inttable_pop(&t->stack));
- assert(color(t, r) == GREEN);
+ UPB_ASSERT(color(t, r) == GREEN);
/* This defines the attr layout for nodes in the WHITE state.
* Top of group stack is [group, NULL]; we point at group. */
setattr(t, r, WHITE | (upb_inttable_count(&t->groups) - 2) << 8);
@@ -3066,19 +3273,19 @@ static upb_refcounted *pop(tarjan *t) {
}
static void tarjan_newgroup(tarjan *t) {
- uint32_t *group = malloc(sizeof(*group));
+ uint32_t *group = upb_gmalloc(sizeof(*group));
if (!group) oom(t);
/* Push group and empty group leader (we'll fill in leader later). */
if (!upb_inttable_push(&t->groups, upb_value_ptr(group)) ||
!upb_inttable_push(&t->groups, upb_value_ptr(NULL))) {
- free(group);
+ upb_gfree(group);
oom(t);
}
*group = 0;
}
static uint32_t idx(tarjan *t, const upb_refcounted *r) {
- assert(color(t, r) == GREEN);
+ UPB_ASSERT(color(t, r) == GREEN);
return (getattr(t, r) >> 2) & 0x7FFFFFFF;
}
@@ -3091,7 +3298,7 @@ static uint32_t lowlink(tarjan *t, const upb_refcounted *r) {
}
static void set_lowlink(tarjan *t, const upb_refcounted *r, uint32_t lowlink) {
- assert(color(t, r) == GREEN);
+ UPB_ASSERT(color(t, r) == GREEN);
setattr(t, r, ((uint64_t)lowlink << 33) | (getattr(t, r) & 0x1FFFFFFFF));
}
@@ -3100,10 +3307,10 @@ static uint32_t *group(tarjan *t, upb_refcounted *r) {
upb_value v;
bool found;
- assert(color(t, r) == WHITE);
+ UPB_ASSERT(color(t, r) == WHITE);
groupnum = getattr(t, r) >> 8;
found = upb_inttable_lookup(&t->groups, groupnum, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
return upb_value_getptr(v);
}
@@ -3114,10 +3321,10 @@ static upb_refcounted *groupleader(tarjan *t, upb_refcounted *r) {
upb_value v;
bool found;
- assert(color(t, r) == WHITE);
+ UPB_ASSERT(color(t, r) == WHITE);
leader_slot = (getattr(t, r) >> 8) + 1;
found = upb_inttable_lookup(&t->groups, leader_slot, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
if (upb_value_getptr(v)) {
return upb_value_getptr(v);
} else {
@@ -3177,7 +3384,7 @@ static void do_tarjan(const upb_refcounted *obj, tarjan *t) {
static void crossref(const upb_refcounted *r, const upb_refcounted *subobj,
void *_t) {
tarjan *t = _t;
- assert(color(t, r) > BLACK);
+ UPB_ASSERT(color(t, r) > BLACK);
if (color(t, subobj) > BLACK && r->group != subobj->group) {
/* Previously this ref was not reflected in subobj->group because they
* were in the same group; now that they are split a ref must be taken. */
@@ -3245,13 +3452,13 @@ static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
upb_refcounted *move = obj->next;
if (obj == move) {
/* Removing the last object from a group. */
- assert(*obj->group == obj->individual_count);
- free(obj->group);
+ UPB_ASSERT(*obj->group == obj->individual_count);
+ upb_gfree(obj->group);
} else {
obj->next = move->next;
/* This may decrease to zero; we'll collect GRAY objects (if any) that
* remain in the group in the third pass. */
- assert(*move->group >= move->individual_count);
+ UPB_ASSERT(*move->group >= move->individual_count);
*move->group -= move->individual_count;
}
@@ -3264,7 +3471,7 @@ static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
*move->group = move->individual_count;
} else {
/* Group already has at least one object in it. */
- assert(leader->group == group(&t, move));
+ UPB_ASSERT(leader->group == group(&t, move));
move->group = group(&t, move);
move->next = leader->next;
leader->next = move;
@@ -3302,7 +3509,7 @@ static bool freeze(upb_refcounted *const*roots, int n, upb_status *s,
/* We eagerly free() the group's count (since we can't easily determine
* the group's remaining size it's the easiest way to ensure it gets
* done). */
- free(obj->group);
+ upb_gfree(obj->group);
/* Visit to release ref2's (done in a separate pass since release_ref2
* depends on o->group being unmodified so it can test merged()). */
@@ -3322,7 +3529,7 @@ err4:
if (!ret) {
upb_inttable_begin(&iter, &t.groups);
for(; !upb_inttable_done(&iter); upb_inttable_next(&iter))
- free(upb_value_getptr(upb_inttable_iter_value(&iter)));
+ upb_gfree(upb_value_getptr(upb_inttable_iter_value(&iter)));
}
upb_inttable_uninit(&t.groups);
err3:
@@ -3346,7 +3553,7 @@ static void merge(upb_refcounted *r, upb_refcounted *from) {
if (merged(r, from)) return;
*r->group += *from->group;
- free(from->group);
+ upb_gfree(from->group);
base = from;
/* Set all refcount pointers in the "from" chain to the merged refcount.
@@ -3354,7 +3561,7 @@ static void merge(upb_refcounted *r, upb_refcounted *from) {
* TODO(haberman): this linear algorithm can result in an overall O(n^2) bound
* if the user continuously extends a group by one object. Prevent this by
* using one of the techniques in this paper:
- * ftp://www.ncedc.org/outgoing/geomorph/dino/orals/p245-tarjan.pdf */
+ * http://bioinfo.ict.ac.cn/~dbu/AlgorithmCourses/Lectures/Union-Find-Tarjan.pdf */
do { from->group = r->group; } while ((from = from->next) != base);
/* Merge the two circularly linked lists by swapping their next pointers. */
@@ -3371,7 +3578,7 @@ static void release_ref2(const upb_refcounted *obj,
UPB_UNUSED(closure);
untrack(subobj, obj, true);
if (!merged(obj, subobj)) {
- assert(subobj->is_frozen);
+ UPB_ASSERT(subobj->is_frozen);
unref(subobj);
}
}
@@ -3380,7 +3587,7 @@ static void unref(const upb_refcounted *r) {
if (unrefgroup(r->group)) {
const upb_refcounted *o;
- free(r->group);
+ upb_gfree(r->group);
/* In two passes, since release_ref2 needs a guarantee that any subobjs
* are alive. */
@@ -3390,7 +3597,7 @@ static void unref(const upb_refcounted *r) {
o = r;
do {
const upb_refcounted *next = o->next;
- assert(o->is_frozen || o->individual_count == 0);
+ UPB_ASSERT(o->is_frozen || o->individual_count == 0);
freeobj((upb_refcounted*)o);
o = next;
} while(o != r);
@@ -3414,9 +3621,9 @@ bool upb_refcounted_init(upb_refcounted *r,
* basically every program using upb. */
const int x = 1;
#ifdef UPB_BIG_ENDIAN
- assert(*(char*)&x != 1);
+ UPB_ASSERT(*(char*)&x != 1);
#else
- assert(*(char*)&x == 1);
+ UPB_ASSERT(*(char*)&x == 1);
#endif
#endif
@@ -3424,13 +3631,10 @@ bool upb_refcounted_init(upb_refcounted *r,
r->vtbl = vtbl;
r->individual_count = 0;
r->is_frozen = false;
- r->group = malloc(sizeof(*r->group));
+ r->group = upb_gmalloc(sizeof(*r->group));
if (!r->group) return false;
*r->group = 0;
- if (!trackinit(r)) {
- free(r->group);
- return false;
- }
+ trackinit(r);
upb_refcounted_ref(r, owner);
return true;
}
@@ -3454,7 +3658,7 @@ void upb_refcounted_unref(const upb_refcounted *r, const void *owner) {
}
void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
- assert(!from->is_frozen); /* Non-const pointer implies this. */
+ UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
track(r, from, true);
if (r->is_frozen) {
refgroup(r->group);
@@ -3464,18 +3668,18 @@ void upb_refcounted_ref2(const upb_refcounted *r, upb_refcounted *from) {
}
void upb_refcounted_unref2(const upb_refcounted *r, upb_refcounted *from) {
- assert(!from->is_frozen); /* Non-const pointer implies this. */
+ UPB_ASSERT(!from->is_frozen); /* Non-const pointer implies this. */
untrack(r, from, true);
if (r->is_frozen) {
unref(r);
} else {
- assert(merged(r, from));
+ UPB_ASSERT(merged(r, from));
}
}
void upb_refcounted_donateref(
const upb_refcounted *r, const void *from, const void *to) {
- assert(from != to);
+ UPB_ASSERT(from != to);
if (to != NULL)
upb_refcounted_ref(r, to);
if (from != NULL)
@@ -3489,15 +3693,16 @@ void upb_refcounted_checkref(const upb_refcounted *r, const void *owner) {
bool upb_refcounted_freeze(upb_refcounted *const*roots, int n, upb_status *s,
int maxdepth) {
int i;
+ bool ret;
for (i = 0; i < n; i++) {
- assert(!roots[i]->is_frozen);
+ UPB_ASSERT(!roots[i]->is_frozen);
}
- return freeze(roots, n, s, maxdepth);
+ ret = freeze(roots, n, s, maxdepth);
+ UPB_ASSERT(!s || ret == upb_ok(s));
+ return ret;
}
-#include <stdlib.h>
-
/* Fallback implementation if the shim is not specialized by the JIT. */
#define SHIM_WRITER(type, ctype) \
bool upb_shim_set ## type (void *c, const void *hd, ctype val) { \
@@ -3523,14 +3728,14 @@ bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER;
bool ok;
- upb_shim_data *d = malloc(sizeof(*d));
+ upb_shim_data *d = upb_gmalloc(sizeof(*d));
if (!d) return false;
d->offset = offset;
d->hasbit = hasbit;
upb_handlerattr_sethandlerdata(&attr, d);
upb_handlerattr_setalwaysok(&attr, true);
- upb_handlers_addcleanup(h, d, free);
+ upb_handlers_addcleanup(h, d, upb_gfree);
#define TYPE(u, l) \
case UPB_TYPE_##u: \
@@ -3547,7 +3752,7 @@ bool upb_shim_set(upb_handlers *h, const upb_fielddef *f, size_t offset,
TYPE(DOUBLE, double);
TYPE(FLOAT, float);
TYPE(BOOL, bool);
- default: assert(false); break;
+ default: UPB_ASSERT(false); break;
}
#undef TYPE
@@ -3581,7 +3786,6 @@ const upb_shim_data *upb_shim_getdata(const upb_handlers *h, upb_selector_t s,
}
-#include <stdlib.h>
#include <string.h>
static void upb_symtab_free(upb_refcounted *r) {
@@ -3593,13 +3797,17 @@ static void upb_symtab_free(upb_refcounted *r) {
upb_def_unref(def, s);
}
upb_strtable_uninit(&s->symtab);
- free(s);
+ upb_gfree(s);
}
-
upb_symtab *upb_symtab_new(const void *owner) {
static const struct upb_refcounted_vtbl vtbl = {NULL, &upb_symtab_free};
- upb_symtab *s = malloc(sizeof(*s));
+
+ upb_symtab *s = upb_gmalloc(sizeof(*s));
+ if (!s) {
+ return NULL;
+ }
+
upb_refcounted_init(upb_symtab_upcast_mutable(s), &vtbl, owner);
upb_strtable_init(&s->symtab, UPB_CTYPE_PTR);
return s;
@@ -3609,13 +3817,13 @@ void upb_symtab_freeze(upb_symtab *s) {
upb_refcounted *r;
bool ok;
- assert(!upb_symtab_isfrozen(s));
+ UPB_ASSERT(!upb_symtab_isfrozen(s));
r = upb_symtab_upcast_mutable(s);
/* The symtab does not take ref2's (see refcounted.h) on the defs, because
* defs cannot refer back to the table and therefore cannot create cycles. So
* 0 will suffice for maxdepth here. */
ok = upb_refcounted_freeze(&r, 1, NULL, 0);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
}
const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym) {
@@ -3653,7 +3861,7 @@ static upb_def *upb_resolvename(const upb_strtable *t,
/* Remove components from base until we find an entry or run out.
* TODO: This branch is totally broken, but currently not used. */
(void)base;
- assert(false);
+ UPB_ASSERT(false);
return NULL;
}
}
@@ -3715,7 +3923,7 @@ static bool upb_resolve_dfs(const upb_def *def, upb_strtable *addtab,
upb_value v;
const upb_msgdef *m;
- assert(upb_def_isfrozen(def));
+ UPB_ASSERT(upb_def_isfrozen(def));
if (def->type == UPB_DEF_FIELD) continue;
if (upb_strtable_lookup(addtab, upb_def_fullname(def), &v)) {
need_dup = true;
@@ -3773,15 +3981,24 @@ oom:
/* TODO(haberman): we need a lot more testing of error conditions.
* The came_from_user stuff in particular is not tested. */
-bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
- upb_status *status) {
- int i;
+static bool symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_refcounted *freeze_also,
+ upb_status *status) {
+ size_t i;
+ size_t add_n;
+ size_t freeze_n;
upb_strtable_iter iter;
+ upb_refcounted **add_objs = NULL;
upb_def **add_defs = NULL;
+ size_t add_objs_size;
upb_strtable addtab;
upb_inttable seen;
- assert(!upb_symtab_isfrozen(s));
+ if (n == 0 && !freeze_also) {
+ return true;
+ }
+
+ UPB_ASSERT(!upb_symtab_isfrozen(s));
if (!upb_strtable_init(&addtab, UPB_CTYPE_PTR)) {
upb_status_seterrmsg(status, "out of memory");
return false;
@@ -3797,7 +4014,7 @@ bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
upb_status_seterrmsg(status, "added defs must be mutable");
goto err;
}
- assert(!upb_def_isfrozen(def));
+ UPB_ASSERT(!upb_def_isfrozen(def));
fullname = upb_def_fullname(def);
if (!fullname) {
upb_status_seterrmsg(
@@ -3841,7 +4058,7 @@ bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
if (!f) continue;
msgname = upb_fielddef_containingtypename(f);
/* We validated this earlier in this function. */
- assert(msgname);
+ UPB_ASSERT(msgname);
/* If the extendee name is absolutely qualified, move past the initial ".".
* TODO(haberman): it is not obvious what it would mean if this was not
@@ -3922,15 +4139,38 @@ bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
}
}
- /* We need an array of the defs in addtab, for passing to upb_def_freeze. */
- add_defs = malloc(sizeof(void*) * upb_strtable_count(&addtab));
+ /* We need an array of the defs in addtab, for passing to
+ * upb_refcounted_freeze(). */
+ add_objs_size = upb_strtable_count(&addtab);
+ if (freeze_also) {
+ add_objs_size++;
+ }
+
+ add_defs = upb_gmalloc(sizeof(void*) * add_objs_size);
if (add_defs == NULL) goto oom_err;
upb_strtable_begin(&iter, &addtab);
- for (n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
- add_defs[n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
+ for (add_n = 0; !upb_strtable_done(&iter); upb_strtable_next(&iter)) {
+ add_defs[add_n++] = upb_value_getptr(upb_strtable_iter_value(&iter));
+ }
+
+ /* Validate defs. */
+ if (!_upb_def_validate(add_defs, add_n, status)) {
+ goto err;
+ }
+
+ /* Cheat a little and give the array a new type.
+ * This is probably undefined behavior, but this code will be deleted soon. */
+ add_objs = (upb_refcounted**)add_defs;
+
+ freeze_n = add_n;
+ if (freeze_also) {
+ add_objs[freeze_n++] = freeze_also;
}
- if (!upb_def_freeze(add_defs, n, status)) goto err;
+ if (!upb_refcounted_freeze(add_objs, freeze_n, status,
+ UPB_MAX_MESSAGE_DEPTH * 2)) {
+ goto err;
+ }
/* This must be delayed until all errors have been detected, since error
* recovery code uses this table to cleanup defs. */
@@ -3938,8 +4178,8 @@ bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
/* TODO(haberman) we don't properly handle errors after this point (like
* OOM in upb_strtable_insert() below). */
- for (i = 0; i < n; i++) {
- upb_def *def = add_defs[i];
+ for (i = 0; i < add_n; i++) {
+ upb_def *def = (upb_def*)add_objs[i];
const char *name = upb_def_fullname(def);
upb_value v;
bool success;
@@ -3949,9 +4189,9 @@ bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
upb_def_unref(def, s);
}
success = upb_strtable_insert(&s->symtab, name, upb_value_ptr(def));
- UPB_ASSERT_VAR(success, success == true);
+ UPB_ASSERT(success == true);
}
- free(add_defs);
+ upb_gfree(add_defs);
return true;
oom_err:
@@ -3972,11 +4212,40 @@ err: {
}
}
upb_strtable_uninit(&addtab);
- free(add_defs);
- assert(!upb_ok(status));
+ upb_gfree(add_defs);
+ UPB_ASSERT(!upb_ok(status));
return false;
}
+bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_status *status) {
+ return symtab_add(s, defs, n, ref_donor, NULL, status);
+}
+
+bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status *status) {
+ size_t n;
+ size_t i;
+ upb_def **defs;
+ bool ret;
+
+ n = upb_filedef_defcount(file);
+ defs = upb_gmalloc(sizeof(*defs) * n);
+
+ if (defs == NULL) {
+ upb_status_seterrmsg(status, "Out of memory");
+ return false;
+ }
+
+ for (i = 0; i < n; i++) {
+ defs[i] = upb_filedef_mutabledef(file, i);
+ }
+
+ ret = symtab_add(s, defs, n, NULL, upb_filedef_upcast_mutable(file), status);
+
+ upb_gfree(defs);
+ return ret;
+}
+
/* Iteration. */
static void advance_to_matching(upb_symtab_iter *iter) {
@@ -4015,7 +4284,6 @@ const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
*/
-#include <stdlib.h>
#include <string.h>
#define UPB_MAXARRSIZE 16 /* 64k. */
@@ -4024,6 +4292,12 @@ const upb_def *upb_symtab_iter_def(const upb_symtab_iter *iter) {
#define ARRAY_SIZE(x) \
((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
+static void upb_check_alloc(upb_table *t, upb_alloc *a) {
+ UPB_UNUSED(t);
+ UPB_UNUSED(a);
+ UPB_ASSERT_DEBUGVAR(t->alloc == a);
+}
+
static const double MAX_LOAD = 0.85;
/* The minimum utilization of the array part of a mixed hash/array table. This
@@ -4041,11 +4315,11 @@ int log2ceil(uint64_t v) {
return UPB_MIN(UPB_MAXARRSIZE, ret);
}
-char *upb_strdup(const char *s) {
- return upb_strdup2(s, strlen(s));
+char *upb_strdup(const char *s, upb_alloc *a) {
+ return upb_strdup2(s, strlen(s), a);
}
-char *upb_strdup2(const char *s, size_t len) {
+char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
size_t n;
char *p;
@@ -4054,7 +4328,7 @@ char *upb_strdup2(const char *s, size_t len) {
/* Always null-terminate, even if binary data; but don't rely on the input to
* have a null-terminating byte since it may be a raw binary buffer. */
n = len + 1;
- p = malloc(n);
+ p = upb_malloc(a, n);
if (p) {
memcpy(p, s, len);
p[len] = 0;
@@ -4095,19 +4369,27 @@ static upb_tabent *mutable_entries(upb_table *t) {
}
static bool isfull(upb_table *t) {
- return (double)(t->count + 1) / upb_table_size(t) > MAX_LOAD;
+ if (upb_table_size(t) == 0) {
+ return true;
+ } else {
+ return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
+ }
}
-static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
+static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
+ upb_alloc *a) {
size_t bytes;
t->count = 0;
t->ctype = ctype;
t->size_lg2 = size_lg2;
t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
+#ifndef NDEBUG
+ t->alloc = a;
+#endif
bytes = upb_table_size(t) * sizeof(upb_tabent);
if (bytes > 0) {
- t->entries = malloc(bytes);
+ t->entries = upb_malloc(a, bytes);
if (!t->entries) return false;
memset(mutable_entries(t), 0, bytes);
} else {
@@ -4116,11 +4398,14 @@ static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2) {
return true;
}
-static void uninit(upb_table *t) { free(mutable_entries(t)); }
+static void uninit(upb_table *t, upb_alloc *a) {
+ upb_check_alloc(t, a);
+ upb_free(a, mutable_entries(t));
+}
static upb_tabent *emptyent(upb_table *t) {
upb_tabent *e = mutable_entries(t) + upb_table_size(t);
- while (1) { if (upb_tabent_isempty(--e)) return e; assert(e > t->entries); }
+ while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
}
static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
@@ -4165,10 +4450,8 @@ static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
upb_tabent *mainpos_e;
upb_tabent *our_e;
- UPB_UNUSED(eql);
- UPB_UNUSED(key);
- assert(findentry(t, key, hash, eql) == NULL);
- assert(val.ctype == t->ctype);
+ UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
+ UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
t->count++;
mainpos_e = getentry_mutable(t, hash);
@@ -4195,7 +4478,7 @@ static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
*new_e = *mainpos_e; /* copies next. */
while (chain->next != mainpos_e) {
chain = (upb_tabent*)chain->next;
- assert(chain);
+ UPB_ASSERT(chain);
}
chain->next = new_e;
our_e = mainpos_e;
@@ -4204,7 +4487,7 @@ static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
}
our_e->key = tabkey;
our_e->val.val = val.val;
- assert(findentry(t, key, hash, eql) == our_e);
+ UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
}
static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
@@ -4214,38 +4497,33 @@ static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
if (eql(chain->key, key)) {
/* Element to remove is at the head of its chain. */
t->count--;
- if (val) {
- _upb_value_setval(val, chain->val.val, t->ctype);
- }
+ if (val) _upb_value_setval(val, chain->val.val, t->ctype);
+ if (removed) *removed = chain->key;
if (chain->next) {
upb_tabent *move = (upb_tabent*)chain->next;
*chain = *move;
- if (removed) *removed = move->key;
move->key = 0; /* Make the slot empty. */
} else {
- if (removed) *removed = chain->key;
chain->key = 0; /* Make the slot empty. */
}
return true;
} else {
/* Element to remove is either in a non-head position or not in the
* table. */
- while (chain->next && !eql(chain->next->key, key))
+ while (chain->next && !eql(chain->next->key, key)) {
chain = (upb_tabent*)chain->next;
+ }
if (chain->next) {
/* Found element to remove. */
- upb_tabent *rm;
-
- if (val) {
- _upb_value_setval(val, chain->next->val.val, t->ctype);
- }
- rm = (upb_tabent*)chain->next;
+ upb_tabent *rm = (upb_tabent*)chain->next;
+ t->count--;
+ if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
if (removed) *removed = rm->key;
- rm->key = 0;
+ rm->key = 0; /* Make the slot empty. */
chain->next = rm->next;
- t->count--;
return true;
} else {
+ /* Element to remove is not in the table. */
return false;
}
}
@@ -4269,8 +4547,8 @@ static size_t begin(const upb_table *t) {
/* A simple "subclass" of upb_table that only adds a hash function for strings. */
-static upb_tabkey strcopy(lookupkey_t k2) {
- char *str = malloc(k2.str.len + sizeof(uint32_t) + 1);
+static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
+ char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
if (str == NULL) return 0;
memcpy(str, &k2.str.len, sizeof(uint32_t));
memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
@@ -4289,51 +4567,56 @@ static bool streql(upb_tabkey k1, lookupkey_t k2) {
return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
}
-bool upb_strtable_init(upb_strtable *t, upb_ctype_t ctype) {
- return init(&t->t, ctype, 2);
+bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
+ return init(&t->t, ctype, 2, a);
}
-void upb_strtable_uninit(upb_strtable *t) {
+void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
size_t i;
for (i = 0; i < upb_table_size(&t->t); i++)
- free((void*)t->t.entries[i].key);
- uninit(&t->t);
+ upb_free(a, (void*)t->t.entries[i].key);
+ uninit(&t->t, a);
}
-bool upb_strtable_resize(upb_strtable *t, size_t size_lg2) {
+bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
upb_strtable new_table;
upb_strtable_iter i;
- if (!init(&new_table.t, t->t.ctype, size_lg2))
+ upb_check_alloc(&t->t, a);
+
+ if (!init(&new_table.t, t->t.ctype, size_lg2, a))
return false;
upb_strtable_begin(&i, t);
for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
- upb_strtable_insert2(
+ upb_strtable_insert3(
&new_table,
upb_strtable_iter_key(&i),
upb_strtable_iter_keylength(&i),
- upb_strtable_iter_value(&i));
+ upb_strtable_iter_value(&i),
+ a);
}
- upb_strtable_uninit(t);
+ upb_strtable_uninit2(t, a);
*t = new_table;
return true;
}
-bool upb_strtable_insert2(upb_strtable *t, const char *k, size_t len,
- upb_value v) {
+bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
+ upb_value v, upb_alloc *a) {
lookupkey_t key;
upb_tabkey tabkey;
uint32_t hash;
+ upb_check_alloc(&t->t, a);
+
if (isfull(&t->t)) {
/* Need to resize. New table of double the size, add old elements to it. */
- if (!upb_strtable_resize(t, t->t.size_lg2 + 1)) {
+ if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
return false;
}
}
key = strkey2(k, len);
- tabkey = strcopy(key);
+ tabkey = strcopy(key, a);
if (tabkey == 0) return false;
hash = MurmurHash2(key.str.str, key.str.len, 0);
@@ -4347,12 +4630,12 @@ bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
return lookup(&t->t, strkey2(key, len), v, hash, &streql);
}
-bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
- upb_value *val) {
- uint32_t hash = MurmurHash2(key, strlen(key), 0);
+bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
+ upb_value *val, upb_alloc *alloc) {
+ uint32_t hash = MurmurHash2(key, len, 0);
upb_tabkey tabkey;
if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
- free((void*)tabkey);
+ upb_free(alloc, (void*)tabkey);
return true;
} else {
return false;
@@ -4379,20 +4662,20 @@ bool upb_strtable_done(const upb_strtable_iter *i) {
upb_tabent_isempty(str_tabent(i));
}
-const char *upb_strtable_iter_key(upb_strtable_iter *i) {
- assert(!upb_strtable_done(i));
+const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
+ UPB_ASSERT(!upb_strtable_done(i));
return upb_tabstr(str_tabent(i)->key, NULL);
}
-size_t upb_strtable_iter_keylength(upb_strtable_iter *i) {
+size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
uint32_t len;
- assert(!upb_strtable_done(i));
+ UPB_ASSERT(!upb_strtable_done(i));
upb_tabstr(str_tabent(i)->key, &len);
return len;
}
upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
- assert(!upb_strtable_done(i));
+ UPB_ASSERT(!upb_strtable_done(i));
return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
}
@@ -4451,26 +4734,26 @@ static void check(upb_inttable *t) {
upb_inttable_iter i;
upb_inttable_begin(&i, t);
for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
- assert(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
+ UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
}
- assert(count == upb_inttable_count(t));
+ UPB_ASSERT(count == upb_inttable_count(t));
}
#endif
}
bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
- size_t asize, int hsize_lg2) {
+ size_t asize, int hsize_lg2, upb_alloc *a) {
size_t array_bytes;
- if (!init(&t->t, ctype, hsize_lg2)) return false;
+ if (!init(&t->t, ctype, hsize_lg2, a)) return false;
/* Always make the array part at least 1 long, so that we know key 0
* won't be in the hash part, which simplifies things. */
t->array_size = UPB_MAX(1, asize);
t->array_count = 0;
array_bytes = t->array_size * sizeof(upb_value);
- t->array = malloc(array_bytes);
+ t->array = upb_malloc(a, array_bytes);
if (!t->array) {
- uninit(&t->t);
+ uninit(&t->t, a);
return false;
}
memset(mutable_array(t), 0xff, array_bytes);
@@ -4478,25 +4761,25 @@ bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
return true;
}
-bool upb_inttable_init(upb_inttable *t, upb_ctype_t ctype) {
- return upb_inttable_sizedinit(t, ctype, 0, 4);
+bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
+ return upb_inttable_sizedinit(t, ctype, 0, 4, a);
}
-void upb_inttable_uninit(upb_inttable *t) {
- uninit(&t->t);
- free(mutable_array(t));
+void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
+ uninit(&t->t, a);
+ upb_free(a, mutable_array(t));
}
-bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
- /* XXX: Table can't store value (uint64_t)-1. Need to somehow statically
- * guarantee that this is not necessary, or fix the limitation. */
+bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
+ upb_alloc *a) {
upb_tabval tabval;
tabval.val = val.val;
- UPB_UNUSED(tabval);
- assert(upb_arrhas(tabval));
+ UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
+
+ upb_check_alloc(&t->t, a);
if (key < t->array_size) {
- assert(!upb_arrhas(t->array[key]));
+ UPB_ASSERT(!upb_arrhas(t->array[key]));
t->array_count++;
mutable_array(t)[key].val = val.val;
} else {
@@ -4504,8 +4787,11 @@ bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
/* Need to resize the hash part, but we re-use the array part. */
size_t i;
upb_table new_table;
- if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1))
+
+ if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
return false;
+ }
+
for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
const upb_tabent *e = &t->t.entries[i];
uint32_t hash;
@@ -4516,9 +4802,9 @@ bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val) {
insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
}
- assert(t->t.count == new_table.count);
+ UPB_ASSERT(t->t.count == new_table.count);
- uninit(&t->t);
+ uninit(&t->t, a);
t->t = new_table;
}
insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
@@ -4556,27 +4842,28 @@ bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
success = false;
}
} else {
- upb_tabkey removed;
- uint32_t hash = upb_inthash(key);
- success = rm(&t->t, intkey(key), val, &removed, hash, &inteql);
+ success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
}
check(t);
return success;
}
-bool upb_inttable_push(upb_inttable *t, upb_value val) {
- return upb_inttable_insert(t, upb_inttable_count(t), val);
+bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
+ upb_check_alloc(&t->t, a);
+ return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
}
upb_value upb_inttable_pop(upb_inttable *t) {
upb_value val;
bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return val;
}
-bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val) {
- return upb_inttable_insert(t, (uintptr_t)key, val);
+bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
+ upb_alloc *a) {
+ upb_check_alloc(&t->t, a);
+ return upb_inttable_insert2(t, (uintptr_t)key, val, a);
}
bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
@@ -4588,77 +4875,74 @@ bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
return upb_inttable_remove(t, (uintptr_t)key, val);
}
-void upb_inttable_compact(upb_inttable *t) {
- /* Create a power-of-two histogram of the table keys. */
- int counts[UPB_MAXARRSIZE + 1] = {0};
- uintptr_t max_key = 0;
+void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
+ /* A power-of-two histogram of the table keys. */
+ size_t counts[UPB_MAXARRSIZE + 1] = {0};
+
+ /* The max key in each bucket. */
+ uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
+
upb_inttable_iter i;
- size_t arr_size;
- int arr_count;
+ size_t arr_count;
+ int size_lg2;
upb_inttable new_t;
+ upb_check_alloc(&t->t, a);
+
upb_inttable_begin(&i, t);
for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
uintptr_t key = upb_inttable_iter_key(&i);
- if (key > max_key) {
- max_key = key;
- }
- counts[log2ceil(key)]++;
+ int bucket = log2ceil(key);
+ max[bucket] = UPB_MAX(max[bucket], key);
+ counts[bucket]++;
}
- arr_size = 1;
+ /* Find the largest power of two that satisfies the MIN_DENSITY
+ * definition (while actually having some keys). */
arr_count = upb_inttable_count(t);
- if (upb_inttable_count(t) >= max_key * MIN_DENSITY) {
- /* We can put 100% of the entries in the array part. */
- arr_size = max_key + 1;
- } else {
- /* Find the largest power of two that satisfies the MIN_DENSITY
- * definition. */
- int size_lg2;
- for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 1; size_lg2--) {
- arr_size = 1 << size_lg2;
- arr_count -= counts[size_lg2];
- if (arr_count >= arr_size * MIN_DENSITY) {
- break;
- }
+ for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
+ if (counts[size_lg2] == 0) {
+ /* We can halve again without losing any entries. */
+ continue;
+ } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
+ break;
}
+
+ arr_count -= counts[size_lg2];
}
- /* Array part must always be at least 1 entry large to catch lookups of key
- * 0. Key 0 must always be in the array part because "0" in the hash part
- * denotes an empty entry. */
- arr_size = UPB_MAX(arr_size, 1);
+ UPB_ASSERT(arr_count <= upb_inttable_count(t));
{
/* Insert all elements into new, perfectly-sized table. */
- int hash_count = upb_inttable_count(t) - arr_count;
- int hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
- int hashsize_lg2 = log2ceil(hash_size);
+ size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
+ size_t hash_count = upb_inttable_count(t) - arr_count;
+ size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
+ size_t hashsize_lg2 = log2ceil(hash_size);
- assert(hash_count >= 0);
- upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2);
+ upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
upb_inttable_begin(&i, t);
for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
uintptr_t k = upb_inttable_iter_key(&i);
- upb_inttable_insert(&new_t, k, upb_inttable_iter_value(&i));
+ upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
}
- assert(new_t.array_size == arr_size);
- assert(new_t.t.size_lg2 == hashsize_lg2);
+ UPB_ASSERT(new_t.array_size == arr_size);
+ UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
}
- upb_inttable_uninit(t);
+ upb_inttable_uninit2(t, a);
*t = new_t;
}
/* Iteration. */
static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
- assert(!i->array_part);
+ UPB_ASSERT(!i->array_part);
return &i->t->t.entries[i->index];
}
static upb_tabval int_arrent(const upb_inttable_iter *i) {
- assert(i->array_part);
+ UPB_ASSERT(i->array_part);
return i->t->array[i->index];
}
@@ -4695,12 +4979,12 @@ bool upb_inttable_done(const upb_inttable_iter *i) {
}
uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
- assert(!upb_inttable_done(i));
+ UPB_ASSERT(!upb_inttable_done(i));
return i->array_part ? i->index : int_tabent(i)->key;
}
upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
- assert(!upb_inttable_done(i));
+ UPB_ASSERT(!upb_inttable_done(i));
return _upb_value_val(
i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
i->t->t.ctype);
@@ -4918,10 +5202,23 @@ bool upb_dumptostderr(void *closure, const upb_status* status) {
static void nullz(upb_status *status) {
const char *ellipsis = "...";
size_t len = strlen(ellipsis);
- assert(sizeof(status->msg) > len);
+ UPB_ASSERT(sizeof(status->msg) > len);
memcpy(status->msg + sizeof(status->msg) - len, ellipsis, len);
}
+
+/* upb_upberr *****************************************************************/
+
+upb_errorspace upb_upberr = {"upb error"};
+
+void upb_upberr_setoom(upb_status *status) {
+ status->error_space_ = &upb_upberr;
+ upb_status_seterrmsg(status, "Out of memory");
+}
+
+
+/* upb_status *****************************************************************/
+
void upb_status_clear(upb_status *status) {
if (!status) return;
status->ok_ = true;
@@ -4960,311 +5257,604 @@ void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args) {
nullz(status);
}
-void upb_status_seterrcode(upb_status *status, upb_errorspace *space,
- int code) {
- if (!status) return;
- status->ok_ = false;
- status->error_space_ = space;
- status->code_ = code;
- space->set_message(status, code);
-}
-
void upb_status_copy(upb_status *to, const upb_status *from) {
if (!to) return;
*to = *from;
}
-/* This file was generated by upbc (the upb compiler).
+
+
+/* upb_alloc ******************************************************************/
+
+static void *upb_global_allocfunc(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size) {
+ UPB_UNUSED(alloc);
+ UPB_UNUSED(oldsize);
+ if (size == 0) {
+ free(ptr);
+ return NULL;
+ } else {
+ return realloc(ptr, size);
+ }
+}
+
+upb_alloc upb_alloc_global = {&upb_global_allocfunc};
+
+
+/* upb_arena ******************************************************************/
+
+/* Be conservative and choose 16 in case anyone is using SSE. */
+static const size_t maxalign = 16;
+
+static size_t align_up(size_t size) {
+ return ((size + maxalign - 1) / maxalign) * maxalign;
+}
+
+typedef struct mem_block {
+ struct mem_block *next;
+ size_t size;
+ size_t used;
+ bool owned;
+ /* Data follows. */
+} mem_block;
+
+typedef struct cleanup_ent {
+ struct cleanup_ent *next;
+ upb_cleanup_func *cleanup;
+ void *ud;
+} cleanup_ent;
+
+static void upb_arena_addblock(upb_arena *a, void *ptr, size_t size,
+ bool owned) {
+ mem_block *block = ptr;
+
+ block->next = a->block_head;
+ block->size = size;
+ block->used = align_up(sizeof(mem_block));
+ block->owned = owned;
+
+ a->block_head = block;
+
+ /* TODO(haberman): ASAN poison. */
+}
+
+
+static mem_block *upb_arena_allocblock(upb_arena *a, size_t size) {
+ size_t block_size = UPB_MAX(size, a->next_block_size) + sizeof(mem_block);
+ mem_block *block = upb_malloc(a->block_alloc, block_size);
+
+ if (!block) {
+ return NULL;
+ }
+
+ upb_arena_addblock(a, block, block_size, true);
+ a->next_block_size = UPB_MIN(block_size * 2, a->max_block_size);
+
+ return block;
+}
+
+static void *upb_arena_doalloc(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size) {
+ upb_arena *a = (upb_arena*)alloc; /* upb_alloc is initial member. */
+ mem_block *block = a->block_head;
+ void *ret;
+
+ if (size == 0) {
+ return NULL; /* We are an arena, don't need individual frees. */
+ }
+
+ size = align_up(size);
+
+ /* TODO(haberman): special-case if this is a realloc of the last alloc? */
+
+ if (!block || block->size - block->used < size) {
+ /* Slow path: have to allocate a new block. */
+ block = upb_arena_allocblock(a, size);
+
+ if (!block) {
+ return NULL; /* Out of memory. */
+ }
+ }
+
+ ret = (char*)block + block->used;
+ block->used += size;
+
+ if (oldsize > 0) {
+ memcpy(ret, ptr, oldsize); /* Preserve existing data. */
+ }
+
+ /* TODO(haberman): ASAN unpoison. */
+
+ a->bytes_allocated += size;
+ return ret;
+}
+
+/* Public Arena API ***********************************************************/
+
+void upb_arena_init(upb_arena *a) {
+ a->alloc.func = &upb_arena_doalloc;
+ a->block_alloc = &upb_alloc_global;
+ a->bytes_allocated = 0;
+ a->next_block_size = 256;
+ a->max_block_size = 16384;
+ a->cleanup_head = NULL;
+ a->block_head = NULL;
+}
+
+void upb_arena_init2(upb_arena *a, void *mem, size_t size, upb_alloc *alloc) {
+ upb_arena_init(a);
+
+ if (size > sizeof(mem_block)) {
+ upb_arena_addblock(a, mem, size, false);
+ }
+
+ if (alloc) {
+ a->block_alloc = alloc;
+ }
+}
+
+void upb_arena_uninit(upb_arena *a) {
+ cleanup_ent *ent = a->cleanup_head;
+ mem_block *block = a->block_head;
+
+ while (ent) {
+ ent->cleanup(ent->ud);
+ ent = ent->next;
+ }
+
+ /* Must do this after running cleanup functions, because this will delete
+ * the memory we store our cleanup entries in! */
+ while (block) {
+ mem_block *next = block->next;
+
+ if (block->owned) {
+ upb_free(a->block_alloc, block);
+ }
+
+ block = next;
+ }
+}
+
+bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud) {
+ cleanup_ent *ent = upb_malloc(&a->alloc, sizeof(cleanup_ent));
+ if (!ent) {
+ return false; /* Out of memory. */
+ }
+
+ ent->cleanup = func;
+ ent->ud = ud;
+ ent->next = a->cleanup_head;
+ a->cleanup_head = ent;
+
+ return true;
+}
+
+size_t upb_arena_bytesallocated(const upb_arena *a) {
+ return a->bytes_allocated;
+}
+
+
+/* Standard error functions ***************************************************/
+
+static bool default_err(void *ud, const upb_status *status) {
+ UPB_UNUSED(ud);
+ UPB_UNUSED(status);
+ return false;
+}
+
+static bool write_err_to(void *ud, const upb_status *status) {
+ upb_status *copy_to = ud;
+ upb_status_copy(copy_to, status);
+ return false;
+}
+
+
+/* upb_env ********************************************************************/
+
+void upb_env_initonly(upb_env *e) {
+ e->ok_ = true;
+ e->error_func_ = &default_err;
+ e->error_ud_ = NULL;
+}
+
+void upb_env_init(upb_env *e) {
+ upb_arena_init(&e->arena_);
+ upb_env_initonly(e);
+}
+
+void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc) {
+ upb_arena_init2(&e->arena_, mem, n, alloc);
+ upb_env_initonly(e);
+}
+
+void upb_env_uninit(upb_env *e) {
+ upb_arena_uninit(&e->arena_);
+}
+
+void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud) {
+ e->error_func_ = func;
+ e->error_ud_ = ud;
+}
+
+void upb_env_reporterrorsto(upb_env *e, upb_status *s) {
+ e->error_func_ = &write_err_to;
+ e->error_ud_ = s;
+}
+
+bool upb_env_reporterror(upb_env *e, const upb_status *status) {
+ e->ok_ = false;
+ return e->error_func_(e->error_ud_, status);
+}
+
+void *upb_env_malloc(upb_env *e, size_t size) {
+ return upb_malloc(&e->arena_.alloc, size);
+}
+
+void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size) {
+ return upb_realloc(&e->arena_.alloc, ptr, oldsize, size);
+}
+
+void upb_env_free(upb_env *e, void *ptr) {
+ upb_free(&e->arena_.alloc, ptr);
+}
+
+bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud) {
+ return upb_arena_addcleanup(&e->arena_, func, ud);
+}
+
+size_t upb_env_bytesallocated(const upb_env *e) {
+ return upb_arena_bytesallocated(&e->arena_);
+}
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * upb/descriptor/descriptor.proto
+ *
* Do not edit -- your changes will be discarded when the file is
* regenerated. */
-static const upb_msgdef msgs[20];
-static const upb_fielddef fields[81];
-static const upb_enumdef enums[4];
+static const upb_msgdef msgs[22];
+static const upb_fielddef fields[105];
+static const upb_enumdef enums[5];
static const upb_tabent strentries[236];
-static const upb_tabent intentries[14];
-static const upb_tabval arrays[232];
+static const upb_tabent intentries[18];
+static const upb_tabval arrays[184];
#ifdef UPB_DEBUG_REFS
-static upb_inttable reftables[212];
+static upb_inttable reftables[264];
#endif
-static const upb_msgdef msgs[20] = {
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 27, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 8, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[0]),&reftables[0], &reftables[1]),
- UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[8], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]),&reftables[2], &reftables[3]),
- UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[20]),&reftables[4], &reftables[5]),
- UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[15], 8, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[24]),&reftables[6], &reftables[7]),
- UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[23], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]),&reftables[8], &reftables[9]),
- UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[27], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[32]),&reftables[10], &reftables[11]),
- UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 19, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 9, 8), UPB_STRTABLE_INIT(8, 15, UPB_CTYPE_PTR, 4, &strentries[36]),&reftables[12], &reftables[13]),
- UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 14, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[40], 32, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[52]),&reftables[14], &reftables[15]),
- UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 39, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[72], 12, 11), UPB_STRTABLE_INIT(11, 15, UPB_CTYPE_PTR, 4, &strentries[68]),&reftables[16], &reftables[17]),
- UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[84], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[84]),&reftables[18], &reftables[19]),
- UPB_MSGDEF_INIT("google.protobuf.FileOptions", 21, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[86], 64, 9), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[88]),&reftables[20], &reftables[21]),
- UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[150], 16, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[104]),&reftables[22], &reftables[23]),
- UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 13, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[166], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[108]),&reftables[24], &reftables[25]),
- UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[10], &arrays[171], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[116]),&reftables[26], &reftables[27]),
- UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[175], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[120]),&reftables[28], &reftables[29]),
- UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 6, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[12], &arrays[179], 4, 0), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[124]),&reftables[30], &reftables[31]),
- UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[183], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[128]),&reftables[32], &reftables[33]),
- UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 14, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[185], 5, 4), UPB_STRTABLE_INIT(4, 7, UPB_CTYPE_PTR, 3, &strentries[132]),&reftables[34], &reftables[35]),
- UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[190], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[140]),&reftables[36], &reftables[37]),
- UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[199], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[156]),&reftables[38], &reftables[39]),
+static const upb_msgdef msgs[22] = {
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto", 40, 8, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[0], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[0]), false, UPB_SYNTAX_PROTO2, &reftables[0], &reftables[1]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ExtensionRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[11], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[16]), false, UPB_SYNTAX_PROTO2, &reftables[2], &reftables[3]),
+ UPB_MSGDEF_INIT("google.protobuf.DescriptorProto.ReservedRange", 4, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[14], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[20]), false, UPB_SYNTAX_PROTO2, &reftables[4], &reftables[5]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[17], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[24]), false, UPB_SYNTAX_PROTO2, &reftables[6], &reftables[7]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumOptions", 8, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[0], &arrays[21], 4, 2), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[28]), false, UPB_SYNTAX_PROTO2, &reftables[8], &reftables[9]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumValueDescriptorProto", 8, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[25], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[32]), false, UPB_SYNTAX_PROTO2, &reftables[10], &reftables[11]),
+ UPB_MSGDEF_INIT("google.protobuf.EnumValueOptions", 7, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[2], &arrays[29], 2, 1), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[36]), false, UPB_SYNTAX_PROTO2, &reftables[12], &reftables[13]),
+ UPB_MSGDEF_INIT("google.protobuf.FieldDescriptorProto", 23, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[31], 11, 10), UPB_STRTABLE_INIT(10, 15, UPB_CTYPE_PTR, 4, &strentries[40]), false, UPB_SYNTAX_PROTO2, &reftables[14], &reftables[15]),
+ UPB_MSGDEF_INIT("google.protobuf.FieldOptions", 12, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[4], &arrays[42], 11, 6), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[56]), false, UPB_SYNTAX_PROTO2, &reftables[16], &reftables[17]),
+ UPB_MSGDEF_INIT("google.protobuf.FileDescriptorProto", 42, 6, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[53], 13, 12), UPB_STRTABLE_INIT(12, 15, UPB_CTYPE_PTR, 4, &strentries[72]), false, UPB_SYNTAX_PROTO2, &reftables[18], &reftables[19]),
+ UPB_MSGDEF_INIT("google.protobuf.FileDescriptorSet", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[66], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[88]), false, UPB_SYNTAX_PROTO2, &reftables[20], &reftables[21]),
+ UPB_MSGDEF_INIT("google.protobuf.FileOptions", 31, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[6], &arrays[68], 39, 15), UPB_STRTABLE_INIT(16, 31, UPB_CTYPE_PTR, 5, &strentries[92]), false, UPB_SYNTAX_PROTO2, &reftables[22], &reftables[23]),
+ UPB_MSGDEF_INIT("google.protobuf.MessageOptions", 10, 1, UPB_INTTABLE_INIT(1, 1, UPB_CTYPE_PTR, 1, &intentries[8], &arrays[107], 8, 4), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[124]), false, UPB_SYNTAX_PROTO2, &reftables[24], &reftables[25]),
+ UPB_MSGDEF_INIT("google.protobuf.MethodDescriptorProto", 15, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[115], 7, 6), UPB_STRTABLE_INIT(6, 7, UPB_CTYPE_PTR, 3, &strentries[132]), false, UPB_SYNTAX_PROTO2, &reftables[26], &reftables[27]),
+ UPB_MSGDEF_INIT("google.protobuf.MethodOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[10], &arrays[122], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[140]), false, UPB_SYNTAX_PROTO2, &reftables[28], &reftables[29]),
+ UPB_MSGDEF_INIT("google.protobuf.OneofDescriptorProto", 5, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[123], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[144]), false, UPB_SYNTAX_PROTO2, &reftables[30], &reftables[31]),
+ UPB_MSGDEF_INIT("google.protobuf.ServiceDescriptorProto", 11, 2, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[125], 4, 3), UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_PTR, 2, &strentries[148]), false, UPB_SYNTAX_PROTO2, &reftables[32], &reftables[33]),
+ UPB_MSGDEF_INIT("google.protobuf.ServiceOptions", 7, 1, UPB_INTTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &intentries[14], &arrays[129], 1, 0), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[152]), false, UPB_SYNTAX_PROTO2, &reftables[34], &reftables[35]),
+ UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo", 6, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[130], 2, 1), UPB_STRTABLE_INIT(1, 3, UPB_CTYPE_PTR, 2, &strentries[156]), false, UPB_SYNTAX_PROTO2, &reftables[36], &reftables[37]),
+ UPB_MSGDEF_INIT("google.protobuf.SourceCodeInfo.Location", 19, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[132], 7, 5), UPB_STRTABLE_INIT(5, 7, UPB_CTYPE_PTR, 3, &strentries[160]), false, UPB_SYNTAX_PROTO2, &reftables[38], &reftables[39]),
+ UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption", 18, 1, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[139], 9, 7), UPB_STRTABLE_INIT(7, 15, UPB_CTYPE_PTR, 4, &strentries[168]), false, UPB_SYNTAX_PROTO2, &reftables[40], &reftables[41]),
+ UPB_MSGDEF_INIT("google.protobuf.UninterpretedOption.NamePart", 6, 0, UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_PTR, 0, NULL, &arrays[148], 3, 2), UPB_STRTABLE_INIT(2, 3, UPB_CTYPE_PTR, 2, &strentries[184]), false, UPB_SYNTAX_PROTO2, &reftables[42], &reftables[43]),
};
-static const upb_fielddef fields[81] = {
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[18], NULL, 15, 6, {0},&reftables[40], &reftables[41]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[3], NULL, 6, 1, {0},&reftables[42], &reftables[43]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[10], NULL, 17, 6, {0},&reftables[44], &reftables[45]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[7], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[46], &reftables[47]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[6], NULL, 16, 7, {0},&reftables[48], &reftables[49]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[8], NULL, 30, 8, {0},&reftables[50], &reftables[51]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[7], NULL, 8, 3, {0},&reftables[52], &reftables[53]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[18], NULL, 11, 4, {0},&reftables[54], &reftables[55]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[56], &reftables[57]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[2]), 16, 2, {0},&reftables[58], &reftables[59]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[8], (const upb_def*)(&msgs[2]), 13, 1, {0},&reftables[60], &reftables[61]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "experimental_map_key", 9, &msgs[7], NULL, 10, 5, {0},&reftables[62], &reftables[63]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[6], NULL, 7, 2, {0},&reftables[64], &reftables[65]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[8], (const upb_def*)(&msgs[6]), 19, 3, {0},&reftables[66], &reftables[67]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[6]), 22, 4, {0},&reftables[68], &reftables[69]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 19, 3, {0},&reftables[70], &reftables[71]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[6]), 10, 0, {0},&reftables[72], &reftables[73]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[9], (const upb_def*)(&msgs[8]), 5, 0, {0},&reftables[74], &reftables[75]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[10], NULL, 14, 5, {0},&reftables[76], &reftables[77]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[18], NULL, 6, 1, {0},&reftables[78], &reftables[79]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[12], NULL, 7, 2, {0},&reftables[80], &reftables[81]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[19], NULL, 5, 1, {0},&reftables[82], &reftables[83]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[10], NULL, 20, 9, {0},&reftables[84], &reftables[85]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[10], NULL, 18, 7, {0},&reftables[86], &reftables[87]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[10], NULL, 13, 4, {0},&reftables[88], &reftables[89]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[10], NULL, 9, 2, {0},&reftables[90], &reftables[91]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[10], NULL, 6, 1, {0},&reftables[92], &reftables[93]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[6], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[94], &reftables[95]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[7], NULL, 9, 4, {0},&reftables[96], &reftables[97]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[17], NULL, 8, 2, {0},&reftables[98], &reftables[99]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[16], (const upb_def*)(&msgs[17]), 5, 0, {0},&reftables[100], &reftables[101]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[11], NULL, 6, 1, {0},&reftables[102], &reftables[103]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[8], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[104], &reftables[105]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[14], (const upb_def*)(&msgs[12]), 6, 0, {0},&reftables[106], &reftables[107]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[8], NULL, 22, 6, {0},&reftables[108], &reftables[109]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[14], NULL, 8, 2, {0},&reftables[110], &reftables[111]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[112], &reftables[113]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[4], NULL, 4, 1, {0},&reftables[114], &reftables[115]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 24, 6, {0},&reftables[116], &reftables[117]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[12], NULL, 4, 1, {0},&reftables[118], &reftables[119]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[2], NULL, 8, 2, {0},&reftables[120], &reftables[121]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[6], NULL, 4, 1, {0},&reftables[122], &reftables[123]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[19], NULL, 2, 0, {0},&reftables[124], &reftables[125]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[18], NULL, 10, 3, {0},&reftables[126], &reftables[127]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 13, 1, {0},&reftables[128], &reftables[129]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[11], NULL, 7, 2, {0},&reftables[130], &reftables[131]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[6], NULL, 10, 3, {0},&reftables[132], &reftables[133]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[4], NULL, 7, 2, {0},&reftables[134], &reftables[135]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[10], (const upb_def*)(&enums[3]), 12, 3, {0},&reftables[136], &reftables[137]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[11]), 23, 5, {0},&reftables[138], &reftables[139]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[2], (const upb_def*)(&msgs[3]), 7, 1, {0},&reftables[140], &reftables[141]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[6], (const upb_def*)(&msgs[7]), 3, 0, {0},&reftables[142], &reftables[143]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[4], (const upb_def*)(&msgs[5]), 3, 0, {0},&reftables[144], &reftables[145]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[8], (const upb_def*)(&msgs[10]), 20, 4, {0},&reftables[146], &reftables[147]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[14], (const upb_def*)(&msgs[15]), 7, 1, {0},&reftables[148], &reftables[149]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[12], (const upb_def*)(&msgs[13]), 3, 0, {0},&reftables[150], &reftables[151]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[12], NULL, 10, 3, {0},&reftables[152], &reftables[153]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[8], NULL, 25, 7, {0},&reftables[154], &reftables[155]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[7], NULL, 7, 2, {0},&reftables[156], &reftables[157]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[17], NULL, 4, 0, {0},&reftables[158], &reftables[159]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[18], NULL, 9, 2, {0},&reftables[160], &reftables[161]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[8], NULL, 35, 9, {0},&reftables[162], &reftables[163]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[10], NULL, 19, 8, {0},&reftables[164], &reftables[165]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[8], (const upb_def*)(&msgs[14]), 16, 2, {0},&reftables[166], &reftables[167]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[8], (const upb_def*)(&msgs[16]), 21, 5, {0},&reftables[168], &reftables[169]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[17], NULL, 7, 1, {0},&reftables[170], &reftables[171]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[172], &reftables[173]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[18], NULL, 12, 5, {0},&reftables[174], &reftables[175]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[17], NULL, 11, 3, {0},&reftables[176], &reftables[177]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[6], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[178], &reftables[179]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[6], NULL, 13, 6, {0},&reftables[180], &reftables[181]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[5], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[182], &reftables[183]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[15], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[184], &reftables[185]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[3], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[186], &reftables[187]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[13], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[188], &reftables[189]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[10], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[190], &reftables[191]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[192], &reftables[193]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[7], (const upb_def*)(&msgs[18]), 5, 0, {0},&reftables[194], &reftables[195]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[2], (const upb_def*)(&msgs[4]), 6, 0, {0},&reftables[196], &reftables[197]),
- UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[7], NULL, 13, 6, {0},&reftables[198], &reftables[199]),
- UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[8], NULL, 38, 10, {0},&reftables[200], &reftables[201]),
+static const upb_fielddef fields[105] = {
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "aggregate_value", 8, &msgs[20], NULL, 15, 6, {0},&reftables[44], &reftables[45]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "allow_alias", 2, &msgs[4], NULL, 6, 1, {0},&reftables[46], &reftables[47]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_enable_arenas", 31, &msgs[11], NULL, 23, 12, {0},&reftables[48], &reftables[49]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "cc_generic_services", 16, &msgs[11], NULL, 17, 6, {0},&reftables[50], &reftables[51]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "client_streaming", 5, &msgs[13], NULL, 13, 4, {0},&reftables[52], &reftables[53]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "csharp_namespace", 37, &msgs[11], NULL, 27, 14, {0},&reftables[54], &reftables[55]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "ctype", 1, &msgs[8], (const upb_def*)(&enums[2]), 6, 1, {0},&reftables[56], &reftables[57]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "default_value", 7, &msgs[7], NULL, 16, 7, {0},&reftables[58], &reftables[59]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "dependency", 3, &msgs[9], NULL, 30, 8, {0},&reftables[60], &reftables[61]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[12], NULL, 8, 3, {0},&reftables[62], &reftables[63]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[8], NULL, 8, 3, {0},&reftables[64], &reftables[65]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[14], NULL, 6, 1, {0},&reftables[66], &reftables[67]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 23, &msgs[11], NULL, 21, 10, {0},&reftables[68], &reftables[69]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 3, &msgs[4], NULL, 7, 2, {0},&reftables[70], &reftables[71]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 33, &msgs[17], NULL, 6, 1, {0},&reftables[72], &reftables[73]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "deprecated", 1, &msgs[6], NULL, 6, 1, {0},&reftables[74], &reftables[75]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_DOUBLE, 0, false, false, false, false, "double_value", 6, &msgs[20], NULL, 11, 4, {0},&reftables[76], &reftables[77]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[2], NULL, 3, 1, {0},&reftables[78], &reftables[79]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "end", 2, &msgs[1], NULL, 3, 1, {0},&reftables[80], &reftables[81]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 4, &msgs[0], (const upb_def*)(&msgs[3]), 18, 2, {0},&reftables[82], &reftables[83]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "enum_type", 5, &msgs[9], (const upb_def*)(&msgs[3]), 13, 1, {0},&reftables[84], &reftables[85]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "extendee", 2, &msgs[7], NULL, 7, 2, {0},&reftables[86], &reftables[87]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 6, &msgs[0], (const upb_def*)(&msgs[7]), 24, 4, {0},&reftables[88], &reftables[89]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension", 7, &msgs[9], (const upb_def*)(&msgs[7]), 19, 3, {0},&reftables[90], &reftables[91]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "extension_range", 5, &msgs[0], (const upb_def*)(&msgs[1]), 21, 3, {0},&reftables[92], &reftables[93]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "field", 2, &msgs[0], (const upb_def*)(&msgs[7]), 12, 0, {0},&reftables[94], &reftables[95]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "file", 1, &msgs[10], (const upb_def*)(&msgs[9]), 5, 0, {0},&reftables[96], &reftables[97]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "go_package", 11, &msgs[11], NULL, 14, 5, {0},&reftables[98], &reftables[99]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "identifier_value", 3, &msgs[20], NULL, 6, 1, {0},&reftables[100], &reftables[101]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "input_type", 2, &msgs[13], NULL, 7, 2, {0},&reftables[102], &reftables[103]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_BOOL, 0, false, false, false, false, "is_extension", 2, &msgs[21], NULL, 5, 1, {0},&reftables[104], &reftables[105]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generate_equals_and_hash", 20, &msgs[11], NULL, 20, 9, {0},&reftables[106], &reftables[107]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_generic_services", 17, &msgs[11], NULL, 18, 7, {0},&reftables[108], &reftables[109]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_multiple_files", 10, &msgs[11], NULL, 13, 4, {0},&reftables[110], &reftables[111]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_outer_classname", 8, &msgs[11], NULL, 9, 2, {0},&reftables[112], &reftables[113]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "java_package", 1, &msgs[11], NULL, 6, 1, {0},&reftables[114], &reftables[115]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "java_string_check_utf8", 27, &msgs[11], NULL, 22, 11, {0},&reftables[116], &reftables[117]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "javanano_use_deprecated_package", 38, &msgs[11], NULL, 30, 15, {0},&reftables[118], &reftables[119]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "json_name", 10, &msgs[7], NULL, 20, 9, {0},&reftables[120], &reftables[121]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "jstype", 6, &msgs[8], (const upb_def*)(&enums[3]), 10, 5, {0},&reftables[122], &reftables[123]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "label", 4, &msgs[7], (const upb_def*)(&enums[0]), 11, 4, {0},&reftables[124], &reftables[125]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "lazy", 5, &msgs[8], NULL, 9, 4, {0},&reftables[126], &reftables[127]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "leading_comments", 3, &msgs[19], NULL, 8, 2, {0},&reftables[128], &reftables[129]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "leading_detached_comments", 6, &msgs[19], NULL, 16, 4, {0},&reftables[130], &reftables[131]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "location", 1, &msgs[18], (const upb_def*)(&msgs[19]), 5, 0, {0},&reftables[132], &reftables[133]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "map_entry", 7, &msgs[12], NULL, 9, 4, {0},&reftables[134], &reftables[135]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "message_set_wire_format", 1, &msgs[12], NULL, 6, 1, {0},&reftables[136], &reftables[137]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "message_type", 4, &msgs[9], (const upb_def*)(&msgs[0]), 10, 0, {0},&reftables[138], &reftables[139]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "method", 2, &msgs[16], (const upb_def*)(&msgs[13]), 6, 0, {0},&reftables[140], &reftables[141]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[3], NULL, 8, 2, {0},&reftables[142], &reftables[143]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[15], NULL, 2, 0, {0},&reftables[144], &reftables[145]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "name", 2, &msgs[20], (const upb_def*)(&msgs[21]), 5, 0, {0},&reftables[146], &reftables[147]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[0], NULL, 32, 8, {0},&reftables[148], &reftables[149]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[5], NULL, 4, 1, {0},&reftables[150], &reftables[151]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[9], NULL, 22, 6, {0},&reftables[152], &reftables[153]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[7], NULL, 4, 1, {0},&reftables[154], &reftables[155]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[13], NULL, 4, 1, {0},&reftables[156], &reftables[157]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "name", 1, &msgs[16], NULL, 8, 2, {0},&reftables[158], &reftables[159]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REQUIRED, UPB_TYPE_STRING, 0, false, false, false, false, "name_part", 1, &msgs[21], NULL, 2, 0, {0},&reftables[160], &reftables[161]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT64, UPB_INTFMT_VARIABLE, false, false, false, false, "negative_int_value", 5, &msgs[20], NULL, 10, 3, {0},&reftables[162], &reftables[163]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "nested_type", 3, &msgs[0], (const upb_def*)(&msgs[0]), 15, 1, {0},&reftables[164], &reftables[165]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "no_standard_descriptor_accessor", 2, &msgs[12], NULL, 7, 2, {0},&reftables[166], &reftables[167]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 2, &msgs[5], NULL, 7, 2, {0},&reftables[168], &reftables[169]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "number", 3, &msgs[7], NULL, 10, 3, {0},&reftables[170], &reftables[171]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "objc_class_prefix", 36, &msgs[11], NULL, 24, 13, {0},&reftables[172], &reftables[173]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "oneof_decl", 8, &msgs[0], (const upb_def*)(&msgs[15]), 28, 6, {0},&reftables[174], &reftables[175]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "oneof_index", 9, &msgs[7], NULL, 19, 8, {0},&reftables[176], &reftables[177]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "optimize_for", 9, &msgs[11], (const upb_def*)(&enums[4]), 12, 3, {0},&reftables[178], &reftables[179]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 7, &msgs[0], (const upb_def*)(&msgs[12]), 25, 5, {0},&reftables[180], &reftables[181]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[9], (const upb_def*)(&msgs[11]), 20, 4, {0},&reftables[182], &reftables[183]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 4, &msgs[13], (const upb_def*)(&msgs[14]), 3, 0, {0},&reftables[184], &reftables[185]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 8, &msgs[7], (const upb_def*)(&msgs[8]), 3, 0, {0},&reftables[186], &reftables[187]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[16], (const upb_def*)(&msgs[17]), 7, 1, {0},&reftables[188], &reftables[189]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[5], (const upb_def*)(&msgs[6]), 3, 0, {0},&reftables[190], &reftables[191]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "options", 3, &msgs[3], (const upb_def*)(&msgs[4]), 7, 1, {0},&reftables[192], &reftables[193]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "output_type", 3, &msgs[13], NULL, 10, 3, {0},&reftables[194], &reftables[195]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "package", 2, &msgs[9], NULL, 25, 7, {0},&reftables[196], &reftables[197]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "packed", 2, &msgs[8], NULL, 7, 2, {0},&reftables[198], &reftables[199]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "path", 1, &msgs[19], NULL, 4, 0, {0},&reftables[200], &reftables[201]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_UINT64, UPB_INTFMT_VARIABLE, false, false, false, false, "positive_int_value", 4, &msgs[20], NULL, 9, 2, {0},&reftables[202], &reftables[203]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "public_dependency", 10, &msgs[9], NULL, 35, 9, {0},&reftables[204], &reftables[205]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "py_generic_services", 18, &msgs[11], NULL, 19, 8, {0},&reftables[206], &reftables[207]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_STRING, 0, false, false, false, false, "reserved_name", 10, &msgs[0], NULL, 37, 9, {0},&reftables[208], &reftables[209]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "reserved_range", 9, &msgs[0], (const upb_def*)(&msgs[2]), 31, 7, {0},&reftables[210], &reftables[211]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "server_streaming", 6, &msgs[13], NULL, 14, 5, {0},&reftables[212], &reftables[213]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "service", 6, &msgs[9], (const upb_def*)(&msgs[16]), 16, 2, {0},&reftables[214], &reftables[215]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_MESSAGE, 0, false, false, false, false, "source_code_info", 9, &msgs[9], (const upb_def*)(&msgs[18]), 21, 5, {0},&reftables[216], &reftables[217]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, true, "span", 2, &msgs[19], NULL, 7, 1, {0},&reftables[218], &reftables[219]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[2], NULL, 2, 0, {0},&reftables[220], &reftables[221]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "start", 1, &msgs[1], NULL, 2, 0, {0},&reftables[222], &reftables[223]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BYTES, 0, false, false, false, false, "string_value", 7, &msgs[20], NULL, 12, 5, {0},&reftables[224], &reftables[225]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "syntax", 12, &msgs[9], NULL, 39, 11, {0},&reftables[226], &reftables[227]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "trailing_comments", 4, &msgs[19], NULL, 11, 3, {0},&reftables[228], &reftables[229]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_ENUM, 0, false, false, false, false, "type", 5, &msgs[7], (const upb_def*)(&enums[1]), 12, 5, {0},&reftables[230], &reftables[231]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_STRING, 0, false, false, false, false, "type_name", 6, &msgs[7], NULL, 13, 6, {0},&reftables[232], &reftables[233]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[11], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[234], &reftables[235]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[12], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[236], &reftables[237]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[6], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[238], &reftables[239]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[4], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[240], &reftables[241]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[8], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[242], &reftables[243]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[14], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[244], &reftables[245]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "uninterpreted_option", 999, &msgs[17], (const upb_def*)(&msgs[20]), 5, 0, {0},&reftables[246], &reftables[247]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_MESSAGE, 0, false, false, false, false, "value", 2, &msgs[3], (const upb_def*)(&msgs[5]), 6, 0, {0},&reftables[248], &reftables[249]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_OPTIONAL, UPB_TYPE_BOOL, 0, false, false, false, false, "weak", 10, &msgs[8], NULL, 11, 6, {0},&reftables[250], &reftables[251]),
+ UPB_FIELDDEF_INIT(UPB_LABEL_REPEATED, UPB_TYPE_INT32, UPB_INTFMT_VARIABLE, false, false, false, false, "weak_dependency", 11, &msgs[9], NULL, 38, 10, {0},&reftables[252], &reftables[253]),
};
-static const upb_enumdef enums[4] = {
- UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[160]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[202], 4, 3), 0, &reftables[202], &reftables[203]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[164]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[206], 19, 18), 0, &reftables[204], &reftables[205]),
- UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[196]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[225], 3, 3), 0, &reftables[206], &reftables[207]),
- UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[200]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[228], 4, 3), 0, &reftables[208], &reftables[209]),
+static const upb_enumdef enums[5] = {
+ UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Label", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[188]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[151], 4, 3), 0, &reftables[254], &reftables[255]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldDescriptorProto.Type", UPB_STRTABLE_INIT(18, 31, UPB_CTYPE_INT32, 5, &strentries[192]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[155], 19, 18), 0, &reftables[256], &reftables[257]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.CType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[224]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[174], 3, 3), 0, &reftables[258], &reftables[259]),
+ UPB_ENUMDEF_INIT("google.protobuf.FieldOptions.JSType", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[228]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[177], 3, 3), 0, &reftables[260], &reftables[261]),
+ UPB_ENUMDEF_INIT("google.protobuf.FileOptions.OptimizeMode", UPB_STRTABLE_INIT(3, 3, UPB_CTYPE_INT32, 2, &strentries[232]), UPB_INTTABLE_INIT(0, 0, UPB_CTYPE_CSTR, 0, NULL, &arrays[180], 4, 3), 0, &reftables[262], &reftables[263]),
};
static const upb_tabent strentries[236] = {
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "reserved_name"), UPB_TABVALUE_PTR_INIT(&fields[82]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[25]), &strentries[12]},
+ {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[24]), &strentries[14]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "field"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
- {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "extension_range"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
+ {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "nested_type"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
+ {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "reserved_range"), UPB_TABVALUE_PTR_INIT(&fields[83]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "oneof_decl"), UPB_TABVALUE_PTR_INIT(&fields[65]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[19]), &strentries[13]},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[89]), NULL},
+ {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[88]), NULL},
+ {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[49]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[9]), &strentries[14]},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "start"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
- {UPB_TABKEY_STR("\003", "\000", "\000", "\000", "end"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[102]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[49]), &strentries[26]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
+ {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "value"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[40]), &strentries[22]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "allow_alias"), UPB_TABVALUE_PTR_INIT(&fields[1]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[34]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[15]), NULL},
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "oneof_index"), UPB_TABVALUE_PTR_INIT(&fields[66]), NULL},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[40]), NULL},
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[52]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[30]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[63]), &strentries[53]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[94]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "json_name"), UPB_TABVALUE_PTR_INIT(&fields[38]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[93]), &strentries[50]},
+ {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "label"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[103]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[41]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "number"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[49]},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "jstype"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "type_name"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
- {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "extendee"), UPB_TABVALUE_PTR_INIT(&fields[12]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "type"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[48]},
- {UPB_TABKEY_STR("\015", "\000", "\000", "\000", "default_value"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "experimental_map_key"), UPB_TABVALUE_PTR_INIT(&fields[11]), &strentries[67]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "weak"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[23]), NULL},
+ {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[104]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[54]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[85]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[86]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "packed"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "lazy"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "syntax"), UPB_TABVALUE_PTR_INIT(&fields[91]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[8]), NULL},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[47]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[69]), &strentries[86]},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), &strentries[85]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "ctype"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[6]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "extension"), UPB_TABVALUE_PTR_INIT(&fields[13]), NULL},
- {UPB_TABKEY_STR("\017", "\000", "\000", "\000", "weak_dependency"), UPB_TABVALUE_PTR_INIT(&fields[80]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "service"), UPB_TABVALUE_PTR_INIT(&fields[63]), NULL},
+ {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[3]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "csharp_namespace"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "source_code_info"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "dependency"), UPB_TABVALUE_PTR_INIT(&fields[5]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "message_type"), UPB_TABVALUE_PTR_INIT(&fields[32]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "package"), UPB_TABVALUE_PTR_INIT(&fields[57]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[53]), &strentries[82]},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "enum_type"), UPB_TABVALUE_PTR_INIT(&fields[10]), NULL},
- {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "public_dependency"), UPB_TABVALUE_PTR_INIT(&fields[61]), &strentries[81]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "file"), UPB_TABVALUE_PTR_INIT(&fields[17]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[27]), NULL},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[120]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "cc_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[24]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[34]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[23]), &strentries[102]},
- {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[22]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "java_multiple_files"), UPB_TABVALUE_PTR_INIT(&fields[33]), &strentries[117]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "go_package"), UPB_TABVALUE_PTR_INIT(&fields[18]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "java_package"), UPB_TABVALUE_PTR_INIT(&fields[26]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
- {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[62]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "java_outer_classname"), UPB_TABVALUE_PTR_INIT(&fields[25]), NULL},
- {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[31]), &strentries[106]},
+ {UPB_TABKEY_STR("\025", "\000", "\000", "\000", "java_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[32]), &strentries[118]},
+ {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "java_generate_equals_and_hash"), UPB_TABVALUE_PTR_INIT(&fields[31]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
- {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
+ {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "javanano_use_deprecated_package"), UPB_TABVALUE_PTR_INIT(&fields[37]), &strentries[123]},
+ {UPB_TABKEY_STR("\023", "\000", "\000", "\000", "py_generic_services"), UPB_TABVALUE_PTR_INIT(&fields[81]), NULL},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "optimize_for"), UPB_TABVALUE_PTR_INIT(&fields[67]), NULL},
+ {UPB_TABKEY_STR("\026", "\000", "\000", "\000", "java_string_check_utf8"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[12]), &strentries[119]},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "objc_class_prefix"), UPB_TABVALUE_PTR_INIT(&fields[64]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "cc_enable_arenas"), UPB_TABVALUE_PTR_INIT(&fields[2]), NULL},
+ {UPB_TABKEY_STR("\027", "\000", "\000", "\000", "message_set_wire_format"), UPB_TABVALUE_PTR_INIT(&fields[46]), &strentries[128]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[39]), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[20]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[9]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "map_entry"), UPB_TABVALUE_PTR_INIT(&fields[45]), NULL},
+ {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "no_standard_descriptor_accessor"), UPB_TABVALUE_PTR_INIT(&fields[61]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[55]), NULL},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "client_streaming"), UPB_TABVALUE_PTR_INIT(&fields[4]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "server_streaming"), UPB_TABVALUE_PTR_INIT(&fields[84]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[56]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "input_type"), UPB_TABVALUE_PTR_INIT(&fields[29]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "output_type"), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[70]), NULL},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[54]), &strentries[122]},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[33]), NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[35]), &strentries[121]},
- {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[72]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[50]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\007", "\000", "\000", "\000", "options"), UPB_TABVALUE_PTR_INIT(&fields[72]), &strentries[150]},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "method"), UPB_TABVALUE_PTR_INIT(&fields[48]), NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[57]), &strentries[149]},
+ {UPB_TABKEY_STR("\024", "\000", "\000", "\000", "uninterpreted_option"), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "deprecated"), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\010", "\000", "\000", "\000", "location"), UPB_TABVALUE_PTR_INIT(&fields[44]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[65]), &strentries[139]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[68]), NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[29]), &strentries[137]},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[7]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "span"), UPB_TABVALUE_PTR_INIT(&fields[87]), &strentries[167]},
+ {UPB_TABKEY_STR("\031", "\000", "\000", "\000", "leading_detached_comments"), UPB_TABVALUE_PTR_INIT(&fields[43]), &strentries[165]},
+ {UPB_TABKEY_STR("\021", "\000", "\000", "\000", "trailing_comments"), UPB_TABVALUE_PTR_INIT(&fields[92]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "leading_comments"), UPB_TABVALUE_PTR_INIT(&fields[42]), &strentries[164]},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "path"), UPB_TABVALUE_PTR_INIT(&fields[78]), NULL},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "double_value"), UPB_TABVALUE_PTR_INIT(&fields[16]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[36]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\004", "\000", "\000", "\000", "name"), UPB_TABVALUE_PTR_INIT(&fields[51]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[43]), NULL},
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "negative_int_value"), UPB_TABVALUE_PTR_INIT(&fields[59]), NULL},
{UPB_TABKEY_STR("\017", "\000", "\000", "\000", "aggregate_value"), UPB_TABVALUE_PTR_INIT(&fields[0]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[60]), NULL},
- {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[19]), NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[67]), &strentries[154]},
+ {UPB_TABKEY_STR("\022", "\000", "\000", "\000", "positive_int_value"), UPB_TABVALUE_PTR_INIT(&fields[79]), NULL},
+ {UPB_TABKEY_STR("\020", "\000", "\000", "\000", "identifier_value"), UPB_TABVALUE_PTR_INIT(&fields[28]), NULL},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "string_value"), UPB_TABVALUE_PTR_INIT(&fields[90]), &strentries[182]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[21]), NULL},
- {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[42]), NULL},
- {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[162]},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "is_extension"), UPB_TABVALUE_PTR_INIT(&fields[30]), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "name_part"), UPB_TABVALUE_PTR_INIT(&fields[58]), NULL},
+ {UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REQUIRED"), UPB_TABVALUE_INT_INIT(2), &strentries[190]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_REPEATED"), UPB_TABVALUE_INT_INIT(3), NULL},
{UPB_TABKEY_STR("\016", "\000", "\000", "\000", "LABEL_OPTIONAL"), UPB_TABVALUE_INT_INIT(1), NULL},
@@ -5274,17 +5864,17 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_STRING"), UPB_TABVALUE_INT_INIT(9), NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[193]},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_FLOAT"), UPB_TABVALUE_INT_INIT(2), &strentries[221]},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_DOUBLE"), UPB_TABVALUE_INT_INIT(1), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT32"), UPB_TABVALUE_INT_INIT(5), NULL},
{UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED32"), UPB_TABVALUE_INT_INIT(15), NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_FIXED32"), UPB_TABVALUE_INT_INIT(7), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[194]},
+ {UPB_TABKEY_STR("\014", "\000", "\000", "\000", "TYPE_MESSAGE"), UPB_TABVALUE_INT_INIT(11), &strentries[222]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[191]},
+ {UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_INT64"), UPB_TABVALUE_INT_INIT(3), &strentries[219]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
@@ -5292,7 +5882,7 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "TYPE_ENUM"), UPB_TABVALUE_INT_INIT(14), NULL},
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT32"), UPB_TABVALUE_INT_INIT(13), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[190]},
+ {UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_UINT64"), UPB_TABVALUE_INT_INIT(4), &strentries[218]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\015", "\000", "\000", "\000", "TYPE_SFIXED64"), UPB_TABVALUE_INT_INIT(16), NULL},
{UPB_TABKEY_STR("\012", "\000", "\000", "\000", "TYPE_BYTES"), UPB_TABVALUE_INT_INIT(12), NULL},
@@ -5302,266 +5892,191 @@ static const upb_tabent strentries[236] = {
{UPB_TABKEY_STR("\013", "\000", "\000", "\000", "TYPE_SINT32"), UPB_TABVALUE_INT_INIT(17), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\004", "\000", "\000", "\000", "CORD"), UPB_TABVALUE_INT_INIT(1), NULL},
- {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[197]},
+ {UPB_TABKEY_STR("\006", "\000", "\000", "\000", "STRING"), UPB_TABVALUE_INT_INIT(0), &strentries[225]},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "STRING_PIECE"), UPB_TABVALUE_INT_INIT(2), NULL},
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NORMAL"), UPB_TABVALUE_INT_INIT(0), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_NUMBER"), UPB_TABVALUE_INT_INIT(2), NULL},
+ {UPB_TABKEY_STR("\011", "\000", "\000", "\000", "JS_STRING"), UPB_TABVALUE_INT_INIT(1), NULL},
{UPB_TABKEY_STR("\011", "\000", "\000", "\000", "CODE_SIZE"), UPB_TABVALUE_INT_INIT(2), NULL},
- {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[203]},
+ {UPB_TABKEY_STR("\005", "\000", "\000", "\000", "SPEED"), UPB_TABVALUE_INT_INIT(1), &strentries[235]},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
{UPB_TABKEY_STR("\014", "\000", "\000", "\000", "LITE_RUNTIME"), UPB_TABVALUE_INT_INIT(3), NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\047", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo.Location"), UPB_TABVALUE_PTR_INIT(&msgs[17]), NULL},
- {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.UninterpretedOption"), UPB_TABVALUE_PTR_INIT(&msgs[18]), NULL},
- {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.FileDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[8]), NULL},
- {UPB_TABKEY_STR("\045", "\000", "\000", "\000", "google.protobuf.MethodDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[12]), NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\040", "\000", "\000", "\000", "google.protobuf.EnumValueOptions"), UPB_TABVALUE_PTR_INIT(&msgs[5]), NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\037", "\000", "\000", "\000", "google.protobuf.DescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[0]), &strentries[228]},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.SourceCodeInfo"), UPB_TABVALUE_PTR_INIT(&msgs[16]), NULL},
- {UPB_TABKEY_STR("\051", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Type"), UPB_TABVALUE_PTR_INIT(&enums[1]), NULL},
- {UPB_TABKEY_STR("\056", "\000", "\000", "\000", "google.protobuf.DescriptorProto.ExtensionRange"), UPB_TABVALUE_PTR_INIT(&msgs[1]), NULL},
- {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.EnumValueDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[4]), NULL},
- {UPB_TABKEY_STR("\034", "\000", "\000", "\000", "google.protobuf.FieldOptions"), UPB_TABVALUE_PTR_INIT(&msgs[7]), NULL},
- {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.FileOptions"), UPB_TABVALUE_PTR_INIT(&msgs[10]), NULL},
- {UPB_TABKEY_STR("\043", "\000", "\000", "\000", "google.protobuf.EnumDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[2]), &strentries[233]},
- {UPB_TABKEY_STR("\052", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto.Label"), UPB_TABVALUE_PTR_INIT(&enums[0]), NULL},
- {UPB_TABKEY_STR("\046", "\000", "\000", "\000", "google.protobuf.ServiceDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[14]), NULL},
- {UPB_TABKEY_STR("\042", "\000", "\000", "\000", "google.protobuf.FieldOptions.CType"), UPB_TABVALUE_PTR_INIT(&enums[2]), &strentries[229]},
- {UPB_TABKEY_STR("\041", "\000", "\000", "\000", "google.protobuf.FileDescriptorSet"), UPB_TABVALUE_PTR_INIT(&msgs[9]), &strentries[235]},
- {UPB_TABKEY_STR("\033", "\000", "\000", "\000", "google.protobuf.EnumOptions"), UPB_TABVALUE_PTR_INIT(&msgs[3]), NULL},
- {UPB_TABKEY_STR("\044", "\000", "\000", "\000", "google.protobuf.FieldDescriptorProto"), UPB_TABVALUE_PTR_INIT(&msgs[6]), NULL},
- {UPB_TABKEY_STR("\050", "\000", "\000", "\000", "google.protobuf.FileOptions.OptimizeMode"), UPB_TABVALUE_PTR_INIT(&enums[3]), &strentries[221]},
- {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.ServiceOptions"), UPB_TABVALUE_PTR_INIT(&msgs[15]), NULL},
- {UPB_TABKEY_STR("\036", "\000", "\000", "\000", "google.protobuf.MessageOptions"), UPB_TABVALUE_PTR_INIT(&msgs[11]), NULL},
- {UPB_TABKEY_STR("\035", "\000", "\000", "\000", "google.protobuf.MethodOptions"), UPB_TABVALUE_PTR_INIT(&msgs[13]), &strentries[226]},
- {UPB_TABKEY_STR("\054", "\000", "\000", "\000", "google.protobuf.UninterpretedOption.NamePart"), UPB_TABVALUE_PTR_INIT(&msgs[19]), NULL},
};
-static const upb_tabent intentries[14] = {
+static const upb_tabent intentries[18] = {
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[98]), NULL},
+ {UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[97]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[73]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[99]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[71]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[95]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[77]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[96]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[75]), NULL},
+ {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[11]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[76]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[100]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[74]), NULL},
+ {UPB_TABKEY_NUM(33), UPB_TABVALUE_PTR_INIT(&fields[14]), NULL},
{UPB_TABKEY_NONE, UPB_TABVALUE_EMPTY_INIT, NULL},
- {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[72]), NULL},
+ {UPB_TABKEY_NUM(999), UPB_TABVALUE_PTR_INIT(&fields[101]), NULL},
};
-static const upb_tabval arrays[232] = {
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[38]),
- UPB_TABVALUE_PTR_INIT(&fields[16]),
- UPB_TABVALUE_PTR_INIT(&fields[44]),
- UPB_TABVALUE_PTR_INIT(&fields[9]),
- UPB_TABVALUE_PTR_INIT(&fields[15]),
- UPB_TABVALUE_PTR_INIT(&fields[14]),
- UPB_TABVALUE_PTR_INIT(&fields[49]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[66]),
- UPB_TABVALUE_PTR_INIT(&fields[8]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[40]),
- UPB_TABVALUE_PTR_INIT(&fields[78]),
- UPB_TABVALUE_PTR_INIT(&fields[50]),
- UPB_TABVALUE_EMPTY_INIT,
+static const upb_tabval arrays[184] = {
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[1]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[37]),
- UPB_TABVALUE_PTR_INIT(&fields[47]),
UPB_TABVALUE_PTR_INIT(&fields[52]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[41]),
- UPB_TABVALUE_PTR_INIT(&fields[12]),
- UPB_TABVALUE_PTR_INIT(&fields[46]),
- UPB_TABVALUE_PTR_INIT(&fields[27]),
- UPB_TABVALUE_PTR_INIT(&fields[69]),
- UPB_TABVALUE_PTR_INIT(&fields[70]),
- UPB_TABVALUE_PTR_INIT(&fields[4]),
- UPB_TABVALUE_PTR_INIT(&fields[51]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[3]),
- UPB_TABVALUE_PTR_INIT(&fields[58]),
- UPB_TABVALUE_PTR_INIT(&fields[6]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[28]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[11]),
- UPB_TABVALUE_PTR_INIT(&fields[79]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[34]),
- UPB_TABVALUE_PTR_INIT(&fields[57]),
- UPB_TABVALUE_PTR_INIT(&fields[5]),
- UPB_TABVALUE_PTR_INIT(&fields[32]),
- UPB_TABVALUE_PTR_INIT(&fields[10]),
- UPB_TABVALUE_PTR_INIT(&fields[63]),
- UPB_TABVALUE_PTR_INIT(&fields[13]),
- UPB_TABVALUE_PTR_INIT(&fields[53]),
- UPB_TABVALUE_PTR_INIT(&fields[64]),
- UPB_TABVALUE_PTR_INIT(&fields[61]),
- UPB_TABVALUE_PTR_INIT(&fields[80]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[17]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[26]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[25]),
- UPB_TABVALUE_PTR_INIT(&fields[48]),
+ UPB_TABVALUE_PTR_INIT(&fields[60]),
+ UPB_TABVALUE_PTR_INIT(&fields[19]),
UPB_TABVALUE_PTR_INIT(&fields[24]),
- UPB_TABVALUE_PTR_INIT(&fields[18]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[2]),
- UPB_TABVALUE_PTR_INIT(&fields[23]),
- UPB_TABVALUE_PTR_INIT(&fields[62]),
- UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT(&fields[22]),
+ UPB_TABVALUE_PTR_INIT(&fields[68]),
+ UPB_TABVALUE_PTR_INIT(&fields[65]),
+ UPB_TABVALUE_PTR_INIT(&fields[83]),
+ UPB_TABVALUE_PTR_INIT(&fields[82]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[89]),
+ UPB_TABVALUE_PTR_INIT(&fields[18]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[88]),
+ UPB_TABVALUE_PTR_INIT(&fields[17]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[49]),
+ UPB_TABVALUE_PTR_INIT(&fields[102]),
+ UPB_TABVALUE_PTR_INIT(&fields[74]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[1]),
+ UPB_TABVALUE_PTR_INIT(&fields[13]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[53]),
+ UPB_TABVALUE_PTR_INIT(&fields[62]),
+ UPB_TABVALUE_PTR_INIT(&fields[73]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[15]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[55]),
+ UPB_TABVALUE_PTR_INIT(&fields[21]),
+ UPB_TABVALUE_PTR_INIT(&fields[63]),
+ UPB_TABVALUE_PTR_INIT(&fields[40]),
+ UPB_TABVALUE_PTR_INIT(&fields[93]),
+ UPB_TABVALUE_PTR_INIT(&fields[94]),
+ UPB_TABVALUE_PTR_INIT(&fields[7]),
+ UPB_TABVALUE_PTR_INIT(&fields[71]),
+ UPB_TABVALUE_PTR_INIT(&fields[66]),
+ UPB_TABVALUE_PTR_INIT(&fields[38]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[6]),
+ UPB_TABVALUE_PTR_INIT(&fields[77]),
+ UPB_TABVALUE_PTR_INIT(&fields[10]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[41]),
+ UPB_TABVALUE_PTR_INIT(&fields[39]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[103]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[54]),
+ UPB_TABVALUE_PTR_INIT(&fields[76]),
+ UPB_TABVALUE_PTR_INIT(&fields[8]),
+ UPB_TABVALUE_PTR_INIT(&fields[47]),
+ UPB_TABVALUE_PTR_INIT(&fields[20]),
+ UPB_TABVALUE_PTR_INIT(&fields[85]),
+ UPB_TABVALUE_PTR_INIT(&fields[23]),
+ UPB_TABVALUE_PTR_INIT(&fields[69]),
+ UPB_TABVALUE_PTR_INIT(&fields[86]),
+ UPB_TABVALUE_PTR_INIT(&fields[80]),
+ UPB_TABVALUE_PTR_INIT(&fields[104]),
+ UPB_TABVALUE_PTR_INIT(&fields[91]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[26]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[35]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[34]),
+ UPB_TABVALUE_PTR_INIT(&fields[67]),
+ UPB_TABVALUE_PTR_INIT(&fields[33]),
+ UPB_TABVALUE_PTR_INIT(&fields[27]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[3]),
+ UPB_TABVALUE_PTR_INIT(&fields[32]),
+ UPB_TABVALUE_PTR_INIT(&fields[81]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[31]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[12]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[36]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[2]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[64]),
+ UPB_TABVALUE_PTR_INIT(&fields[5]),
+ UPB_TABVALUE_PTR_INIT(&fields[37]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[46]),
+ UPB_TABVALUE_PTR_INIT(&fields[61]),
+ UPB_TABVALUE_PTR_INIT(&fields[9]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[31]),
UPB_TABVALUE_PTR_INIT(&fields[45]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[39]),
- UPB_TABVALUE_PTR_INIT(&fields[20]),
UPB_TABVALUE_PTR_INIT(&fields[56]),
- UPB_TABVALUE_PTR_INIT(&fields[55]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[29]),
+ UPB_TABVALUE_PTR_INIT(&fields[75]),
+ UPB_TABVALUE_PTR_INIT(&fields[70]),
+ UPB_TABVALUE_PTR_INIT(&fields[4]),
+ UPB_TABVALUE_PTR_INIT(&fields[84]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[50]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[35]),
- UPB_TABVALUE_PTR_INIT(&fields[33]),
- UPB_TABVALUE_PTR_INIT(&fields[54]),
+ UPB_TABVALUE_PTR_INIT(&fields[57]),
+ UPB_TABVALUE_PTR_INIT(&fields[48]),
+ UPB_TABVALUE_PTR_INIT(&fields[72]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[44]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[78]),
+ UPB_TABVALUE_PTR_INIT(&fields[87]),
+ UPB_TABVALUE_PTR_INIT(&fields[42]),
+ UPB_TABVALUE_PTR_INIT(&fields[92]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[43]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[30]),
UPB_TABVALUE_EMPTY_INIT,
+ UPB_TABVALUE_PTR_INIT(&fields[51]),
+ UPB_TABVALUE_PTR_INIT(&fields[28]),
+ UPB_TABVALUE_PTR_INIT(&fields[79]),
UPB_TABVALUE_PTR_INIT(&fields[59]),
- UPB_TABVALUE_PTR_INIT(&fields[65]),
- UPB_TABVALUE_PTR_INIT(&fields[29]),
- UPB_TABVALUE_PTR_INIT(&fields[68]),
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[36]),
- UPB_TABVALUE_PTR_INIT(&fields[19]),
- UPB_TABVALUE_PTR_INIT(&fields[60]),
- UPB_TABVALUE_PTR_INIT(&fields[43]),
- UPB_TABVALUE_PTR_INIT(&fields[7]),
- UPB_TABVALUE_PTR_INIT(&fields[67]),
+ UPB_TABVALUE_PTR_INIT(&fields[16]),
+ UPB_TABVALUE_PTR_INIT(&fields[90]),
UPB_TABVALUE_PTR_INIT(&fields[0]),
UPB_TABVALUE_EMPTY_INIT,
- UPB_TABVALUE_PTR_INIT(&fields[42]),
- UPB_TABVALUE_PTR_INIT(&fields[21]),
+ UPB_TABVALUE_PTR_INIT(&fields[58]),
+ UPB_TABVALUE_PTR_INIT(&fields[30]),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT("LABEL_OPTIONAL"),
UPB_TABVALUE_PTR_INIT("LABEL_REQUIRED"),
@@ -5588,21 +6103,69 @@ static const upb_tabval arrays[232] = {
UPB_TABVALUE_PTR_INIT("STRING"),
UPB_TABVALUE_PTR_INIT("CORD"),
UPB_TABVALUE_PTR_INIT("STRING_PIECE"),
+ UPB_TABVALUE_PTR_INIT("JS_NORMAL"),
+ UPB_TABVALUE_PTR_INIT("JS_STRING"),
+ UPB_TABVALUE_PTR_INIT("JS_NUMBER"),
UPB_TABVALUE_EMPTY_INIT,
UPB_TABVALUE_PTR_INIT("SPEED"),
UPB_TABVALUE_PTR_INIT("CODE_SIZE"),
UPB_TABVALUE_PTR_INIT("LITE_RUNTIME"),
};
-static const upb_symtab symtab = UPB_SYMTAB_INIT(UPB_STRTABLE_INIT(24, 31, UPB_CTYPE_PTR, 5, &strentries[204]), &reftables[210], &reftables[211]);
-
-const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner) {
- upb_symtab_ref(&symtab, owner);
- return &symtab;
-}
-
#ifdef UPB_DEBUG_REFS
-static upb_inttable reftables[212] = {
+static upb_inttable reftables[264] = {
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
+ UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),
@@ -5818,6 +6381,45 @@ static upb_inttable reftables[212] = {
};
#endif
+static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {
+ upb_msgdef_ref(m, owner);
+ return m;
+}
+
+static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {
+ upb_enumdef_ref(e, owner);
+ return e;
+}
+
+/* Public API. */
+const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_get(const void *owner) { return refm(&msgs[0], owner); }
+const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(const void *owner) { return refm(&msgs[1], owner); }
+const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner) { return refm(&msgs[2], owner); }
+const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner) { return refm(&msgs[3], owner); }
+const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner) { return refm(&msgs[4], owner); }
+const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner) { return refm(&msgs[5], owner); }
+const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner) { return refm(&msgs[6], owner); }
+const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner) { return refm(&msgs[7], owner); }
+const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner) { return refm(&msgs[8], owner); }
+const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner) { return refm(&msgs[9], owner); }
+const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner) { return refm(&msgs[10], owner); }
+const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner) { return refm(&msgs[11], owner); }
+const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner) { return refm(&msgs[12], owner); }
+const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner) { return refm(&msgs[13], owner); }
+const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner) { return refm(&msgs[14], owner); }
+const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner) { return refm(&msgs[15], owner); }
+const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner) { return refm(&msgs[16], owner); }
+const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner) { return refm(&msgs[17], owner); }
+const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner) { return refm(&msgs[18], owner); }
+const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner) { return refm(&msgs[19], owner); }
+const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner) { return refm(&msgs[20], owner); }
+const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner) { return refm(&msgs[21], owner); }
+
+const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner) { return refe(&enums[0], owner); }
+const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner) { return refe(&enums[1], owner); }
+const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner) { return refe(&enums[2], owner); }
+const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner) { return refe(&enums[3], owner); }
+const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner) { return refe(&enums[4], owner); }
/*
** XXX: The routines in this file that consume a string do not currently
** support having the string span buffers. In the future, as upb_sink and
@@ -5831,14 +6433,10 @@ static upb_inttable reftables[212] = {
#include <stdlib.h>
#include <string.h>
-/* upb_deflist is an internal-only dynamic array for storing a growing list of
- * upb_defs. */
-typedef struct {
- upb_def **defs;
- size_t len;
- size_t size;
- bool owned;
-} upb_deflist;
+/* Compares a NULL-terminated string with a non-NULL-terminated string. */
+static bool upb_streq(const char *str, const char *buf, size_t n) {
+ return strlen(str) == n && memcmp(str, buf, n) == 0;
+}
/* We keep a stack of all the messages scopes we are currently in, as well as
* the top-level file scope. This is necessary to correctly qualify the
@@ -5849,6 +6447,8 @@ typedef struct {
/* Index of the first def that is under this scope. For msgdefs, the
* msgdef itself is at start-1. */
int start;
+ uint32_t oneof_start;
+ uint32_t oneof_index;
} upb_descreader_frame;
/* The maximum number of nested declarations that are allowed, ie.
@@ -5865,9 +6465,11 @@ typedef struct {
struct upb_descreader {
upb_sink sink;
- upb_deflist defs;
+ upb_inttable files;
+ upb_filedef *file; /* The last file in files. */
upb_descreader_frame stack[UPB_MAX_MESSAGE_NESTING];
int stack_len;
+ upb_inttable oneofs;
uint32_t number;
char *name;
@@ -5880,7 +6482,7 @@ struct upb_descreader {
};
static char *upb_strndup(const char *buf, size_t n) {
- char *ret = malloc(n + 1);
+ char *ret = upb_gmalloc(n + 1);
if (!ret) return NULL;
memcpy(ret, buf, n);
ret[n] = '\0';
@@ -5894,9 +6496,12 @@ static char *upb_strndup(const char *buf, size_t n) {
* Caller owns a ref on the returned string. */
static char *upb_join(const char *base, const char *name) {
if (!base || strlen(base) == 0) {
- return upb_strdup(name);
+ return upb_gstrdup(name);
} else {
- char *ret = malloc(strlen(base) + strlen(name) + 2);
+ char *ret = upb_gmalloc(strlen(base) + strlen(name) + 2);
+ if (!ret) {
+ return NULL;
+ }
ret[0] = '\0';
strcat(ret, base);
strcat(ret, ".");
@@ -5905,57 +6510,21 @@ static char *upb_join(const char *base, const char *name) {
}
}
-
-/* upb_deflist ****************************************************************/
-
-void upb_deflist_init(upb_deflist *l) {
- l->size = 0;
- l->defs = NULL;
- l->len = 0;
- l->owned = true;
-}
-
-void upb_deflist_uninit(upb_deflist *l) {
- size_t i;
- if (l->owned)
- for(i = 0; i < l->len; i++)
- upb_def_unref(l->defs[i], l);
- free(l->defs);
-}
-
-bool upb_deflist_push(upb_deflist *l, upb_def *d) {
- if(++l->len >= l->size) {
- size_t new_size = UPB_MAX(l->size, 4);
- new_size *= 2;
- l->defs = realloc(l->defs, new_size * sizeof(void *));
- if (!l->defs) return false;
- l->size = new_size;
- }
- l->defs[l->len - 1] = d;
- return true;
-}
-
-void upb_deflist_donaterefs(upb_deflist *l, void *owner) {
- size_t i;
- assert(l->owned);
- for (i = 0; i < l->len; i++)
- upb_def_donateref(l->defs[i], l, owner);
- l->owned = false;
-}
-
-static upb_def *upb_deflist_last(upb_deflist *l) {
- return l->defs[l->len-1];
-}
-
/* Qualify the defname for all defs starting with offset "start" with "str". */
-static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
- uint32_t i;
- for (i = start; i < l->len; i++) {
- upb_def *def = l->defs[i];
+static bool upb_descreader_qualify(upb_filedef *f, char *str, int32_t start) {
+ size_t i;
+ for (i = start; i < upb_filedef_defcount(f); i++) {
+ upb_def *def = upb_filedef_mutabledef(f, i);
char *name = upb_join(str, upb_def_fullname(def));
+ if (!name) {
+ /* Need better logic here; at this point we've qualified some names but
+ * not others. */
+ return false;
+ }
upb_def_setfullname(def, name, NULL);
- free(name);
+ upb_gfree(name);
}
+ return true;
}
@@ -5963,63 +6532,178 @@ static void upb_deflist_qualify(upb_deflist *l, char *str, int32_t start) {
static upb_msgdef *upb_descreader_top(upb_descreader *r) {
int index;
- assert(r->stack_len > 1);
+ UPB_ASSERT(r->stack_len > 1);
index = r->stack[r->stack_len-1].start - 1;
- assert(index >= 0);
- return upb_downcast_msgdef_mutable(r->defs.defs[index]);
+ UPB_ASSERT(index >= 0);
+ return upb_downcast_msgdef_mutable(upb_filedef_mutabledef(r->file, index));
}
static upb_def *upb_descreader_last(upb_descreader *r) {
- return upb_deflist_last(&r->defs);
+ return upb_filedef_mutabledef(r->file, upb_filedef_defcount(r->file) - 1);
}
/* Start/end handlers for FileDescriptorProto and DescriptorProto (the two
* entities that have names and can contain sub-definitions. */
void upb_descreader_startcontainer(upb_descreader *r) {
upb_descreader_frame *f = &r->stack[r->stack_len++];
- f->start = r->defs.len;
+ f->start = upb_filedef_defcount(r->file);
+ f->oneof_start = upb_inttable_count(&r->oneofs);
+ f->oneof_index = 0;
f->name = NULL;
}
-void upb_descreader_endcontainer(upb_descreader *r) {
- upb_descreader_frame *f = &r->stack[--r->stack_len];
- upb_deflist_qualify(&r->defs, f->name, f->start);
- free(f->name);
+bool upb_descreader_endcontainer(upb_descreader *r) {
+ upb_descreader_frame *f = &r->stack[r->stack_len - 1];
+
+ while (upb_inttable_count(&r->oneofs) > f->oneof_start) {
+ upb_oneofdef *o = upb_value_getptr(upb_inttable_pop(&r->oneofs));
+ bool ok = upb_msgdef_addoneof(upb_descreader_top(r), o, &r->oneofs, NULL);
+ UPB_ASSERT(ok);
+ }
+
+ if (!upb_descreader_qualify(r->file, f->name, f->start)) {
+ return false;
+ }
+ upb_gfree(f->name);
f->name = NULL;
+
+ r->stack_len--;
+ return true;
}
void upb_descreader_setscopename(upb_descreader *r, char *str) {
upb_descreader_frame *f = &r->stack[r->stack_len-1];
- free(f->name);
+ upb_gfree(f->name);
f->name = str;
}
-/* Handlers for google.protobuf.FileDescriptorProto. */
-static bool file_startmsg(void *r, const void *hd) {
+static upb_oneofdef *upb_descreader_getoneof(upb_descreader *r,
+ uint32_t index) {
+ bool found;
+ upb_value val;
+ upb_descreader_frame *f = &r->stack[r->stack_len-1];
+
+ /* DescriptorProto messages can be nested, so we will see the nested messages
+ * between when we see the FieldDescriptorProto and the OneofDescriptorProto.
+ * We need to preserve the oneofs in between these two things. */
+ index += f->oneof_start;
+
+ while (upb_inttable_count(&r->oneofs) <= index) {
+ upb_inttable_push(&r->oneofs, upb_value_ptr(upb_oneofdef_new(&r->oneofs)));
+ }
+
+ found = upb_inttable_lookup(&r->oneofs, index, &val);
+ UPB_ASSERT(found);
+ return upb_value_getptr(val);
+}
+
+/** Handlers for google.protobuf.FileDescriptorSet. ***************************/
+
+static void *fileset_startfile(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ UPB_UNUSED(hd);
+ r->file = upb_filedef_new(&r->files);
+ upb_inttable_push(&r->files, upb_value_ptr(r->file));
+ return r;
+}
+
+/** Handlers for google.protobuf.FileDescriptorProto. *************************/
+
+static bool file_start(void *closure, const void *hd) {
+ upb_descreader *r = closure;
UPB_UNUSED(hd);
upb_descreader_startcontainer(r);
return true;
}
-static bool file_endmsg(void *closure, const void *hd, upb_status *status) {
+static bool file_end(void *closure, const void *hd, upb_status *status) {
upb_descreader *r = closure;
UPB_UNUSED(hd);
UPB_UNUSED(status);
- upb_descreader_endcontainer(r);
- return true;
+ return upb_descreader_endcontainer(r);
+}
+
+static size_t file_onname(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ char *name;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ name = upb_strndup(buf, n);
+ /* XXX: see comment at the top of the file. */
+ ok = upb_filedef_setname(r->file, name, NULL);
+ upb_gfree(name);
+ UPB_ASSERT(ok);
+ return n;
}
static size_t file_onpackage(void *closure, const void *hd, const char *buf,
size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
+ char *package;
+ bool ok;
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ package = upb_strndup(buf, n);
+ /* XXX: see comment at the top of the file. */
+ upb_descreader_setscopename(r, package);
+ ok = upb_filedef_setpackage(r->file, package, NULL);
+ UPB_ASSERT(ok);
+ return n;
+}
+
+static size_t file_onsyntax(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ bool ok;
UPB_UNUSED(hd);
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
- upb_descreader_setscopename(r, upb_strndup(buf, n));
+ if (upb_streq("proto2", buf, n)) {
+ ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO2, NULL);
+ } else if (upb_streq("proto3", buf, n)) {
+ ok = upb_filedef_setsyntax(r->file, UPB_SYNTAX_PROTO3, NULL);
+ } else {
+ ok = false;
+ }
+
+ UPB_ASSERT(ok);
return n;
}
-/* Handlers for google.protobuf.EnumValueDescriptorProto. */
+static void *file_startmsg(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ upb_msgdef *m = upb_msgdef_new(&m);
+ bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
+ UPB_UNUSED(hd);
+ UPB_ASSERT(ok);
+ return r;
+}
+
+static void *file_startenum(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ upb_enumdef *e = upb_enumdef_new(&e);
+ bool ok = upb_filedef_addenum(r->file, e, &e, NULL);
+ UPB_UNUSED(hd);
+ UPB_ASSERT(ok);
+ return r;
+}
+
+static void *file_startext(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ bool ok;
+ r->f = upb_fielddef_new(r);
+ ok = upb_filedef_addext(r->file, r->f, r, NULL);
+ UPB_UNUSED(hd);
+ UPB_ASSERT(ok);
+ return r;
+}
+
+/** Handlers for google.protobuf.EnumValueDescriptorProto. *********************/
+
static bool enumval_startmsg(void *closure, const void *hd) {
upb_descreader *r = closure;
UPB_UNUSED(hd);
@@ -6034,7 +6718,7 @@ static size_t enumval_onname(void *closure, const void *hd, const char *buf,
UPB_UNUSED(hd);
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
- free(r->name);
+ upb_gfree(r->name);
r->name = upb_strndup(buf, n);
r->saw_name = true;
return n;
@@ -6059,20 +6743,12 @@ static bool enumval_endmsg(void *closure, const void *hd, upb_status *status) {
}
e = upb_downcast_enumdef_mutable(upb_descreader_last(r));
upb_enumdef_addval(e, r->name, r->number, status);
- free(r->name);
+ upb_gfree(r->name);
r->name = NULL;
return true;
}
-
-/* Handlers for google.protobuf.EnumDescriptorProto. */
-static bool enum_startmsg(void *closure, const void *hd) {
- upb_descreader *r = closure;
- UPB_UNUSED(hd);
- upb_deflist_push(&r->defs,
- upb_enumdef_upcast_mutable(upb_enumdef_new(&r->defs)));
- return true;
-}
+/** Handlers for google.protobuf.EnumDescriptorProto. *************************/
static bool enum_endmsg(void *closure, const void *hd, upb_status *status) {
upb_descreader *r = closure;
@@ -6099,16 +6775,17 @@ static size_t enum_onname(void *closure, const void *hd, const char *buf,
UPB_UNUSED(handle);
/* XXX: see comment at the top of the file. */
upb_def_setfullname(upb_descreader_last(r), fullname, NULL);
- free(fullname);
+ upb_gfree(fullname);
return n;
}
-/* Handlers for google.protobuf.FieldDescriptorProto */
+/** Handlers for google.protobuf.FieldDescriptorProto *************************/
+
static bool field_startmsg(void *closure, const void *hd) {
upb_descreader *r = closure;
UPB_UNUSED(hd);
- r->f = upb_fielddef_new(&r->defs);
- free(r->default_string);
+ UPB_ASSERT(r->f);
+ upb_gfree(r->default_string);
r->default_string = NULL;
/* fielddefs default to packed, but descriptors default to non-packed. */
@@ -6193,9 +6870,9 @@ static bool field_endmsg(void *closure, const void *hd, upb_status *status) {
UPB_UNUSED(hd);
/* TODO: verify that all required fields were present. */
- assert(upb_fielddef_number(f) != 0);
- assert(upb_fielddef_name(f) != NULL);
- assert((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
+ UPB_ASSERT(upb_fielddef_number(f) != 0);
+ UPB_ASSERT(upb_fielddef_name(f) != NULL);
+ UPB_ASSERT((upb_fielddef_subdefname(f) != NULL) == upb_fielddef_hassubdef(f));
if (r->default_string) {
if (upb_fielddef_issubmsg(f)) {
@@ -6250,10 +6927,11 @@ static bool field_onlabel(void *closure, const void *hd, int32_t val) {
static bool field_onnumber(void *closure, const void *hd, int32_t val) {
upb_descreader *r = closure;
- bool ok = upb_fielddef_setnumber(r->f, val, NULL);
+ bool ok;
UPB_UNUSED(hd);
- UPB_ASSERT_VAR(ok, ok);
+ ok = upb_fielddef_setnumber(r->f, val, NULL);
+ UPB_ASSERT(ok);
return true;
}
@@ -6266,7 +6944,7 @@ static size_t field_onname(void *closure, const void *hd, const char *buf,
/* XXX: see comment at the top of the file. */
upb_fielddef_setname(r->f, name, NULL);
- free(name);
+ upb_gfree(name);
return n;
}
@@ -6279,7 +6957,7 @@ static size_t field_ontypename(void *closure, const void *hd, const char *buf,
/* XXX: see comment at the top of the file. */
upb_fielddef_setsubdefname(r->f, name, NULL);
- free(name);
+ upb_gfree(name);
return n;
}
@@ -6292,7 +6970,7 @@ static size_t field_onextendee(void *closure, const void *hd, const char *buf,
/* XXX: see comment at the top of the file. */
upb_fielddef_setcontainingtypename(r->f, name, NULL);
- free(name);
+ upb_gfree(name);
return n;
}
@@ -6305,23 +6983,49 @@ static size_t field_ondefaultval(void *closure, const void *hd, const char *buf,
/* Have to convert from string to the correct type, but we might not know the
* type yet, so we save it as a string until the end of the field.
* XXX: see comment at the top of the file. */
- free(r->default_string);
+ upb_gfree(r->default_string);
r->default_string = upb_strndup(buf, n);
return n;
}
-/* Handlers for google.protobuf.DescriptorProto (representing a message). */
-static bool msg_startmsg(void *closure, const void *hd) {
+static bool field_ononeofindex(void *closure, const void *hd, int32_t index) {
+ upb_descreader *r = closure;
+ upb_oneofdef *o = upb_descreader_getoneof(r, index);
+ bool ok = upb_oneofdef_addfield(o, r->f, &r->f, NULL);
+ UPB_UNUSED(hd);
+
+ UPB_ASSERT(ok);
+ return true;
+}
+
+/** Handlers for google.protobuf.OneofDescriptorProto. ************************/
+
+static size_t oneof_name(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
+ upb_descreader *r = closure;
+ upb_descreader_frame *f = &r->stack[r->stack_len-1];
+ upb_oneofdef *o = upb_descreader_getoneof(r, f->oneof_index++);
+ char *name_null_terminated = upb_strndup(buf, n);
+ bool ok = upb_oneofdef_setname(o, name_null_terminated, NULL);
+ UPB_UNUSED(hd);
+ UPB_UNUSED(handle);
+
+ UPB_ASSERT(ok);
+ free(name_null_terminated);
+ return n;
+}
+
+/** Handlers for google.protobuf.DescriptorProto ******************************/
+
+static bool msg_start(void *closure, const void *hd) {
upb_descreader *r = closure;
UPB_UNUSED(hd);
- upb_deflist_push(&r->defs,
- upb_msgdef_upcast_mutable(upb_msgdef_new(&r->defs)));
upb_descreader_startcontainer(r);
return true;
}
-static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
+static bool msg_end(void *closure, const void *hd, upb_status *status) {
upb_descreader *r = closure;
upb_msgdef *m = upb_descreader_top(r);
UPB_UNUSED(hd);
@@ -6330,12 +7034,11 @@ static bool msg_endmsg(void *closure, const void *hd, upb_status *status) {
upb_status_seterrmsg(status, "Encountered message with no name.");
return false;
}
- upb_descreader_endcontainer(r);
- return true;
+ return upb_descreader_endcontainer(r);
}
-static size_t msg_onname(void *closure, const void *hd, const char *buf,
- size_t n, const upb_bufhandle *handle) {
+static size_t msg_name(void *closure, const void *hd, const char *buf,
+ size_t n, const upb_bufhandle *handle) {
upb_descreader *r = closure;
upb_msgdef *m = upb_descreader_top(r);
/* XXX: see comment at the top of the file. */
@@ -6348,91 +7051,158 @@ static size_t msg_onname(void *closure, const void *hd, const char *buf,
return n;
}
-static bool msg_onendfield(void *closure, const void *hd) {
+static void *msg_startmsg(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ upb_msgdef *m = upb_msgdef_new(&m);
+ bool ok = upb_filedef_addmsg(r->file, m, &m, NULL);
+ UPB_UNUSED(hd);
+ UPB_ASSERT(ok);
+ return r;
+}
+
+static void *msg_startext(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ upb_fielddef *f = upb_fielddef_new(&f);
+ bool ok = upb_filedef_addext(r->file, f, &f, NULL);
+ UPB_UNUSED(hd);
+ UPB_ASSERT(ok);
+ return r;
+}
+
+static void *msg_startfield(void *closure, const void *hd) {
+ upb_descreader *r = closure;
+ r->f = upb_fielddef_new(&r->f);
+ /* We can't add the new field to the message until its name/number are
+ * filled in. */
+ UPB_UNUSED(hd);
+ return r;
+}
+
+static bool msg_endfield(void *closure, const void *hd) {
upb_descreader *r = closure;
upb_msgdef *m = upb_descreader_top(r);
+ bool ok;
UPB_UNUSED(hd);
- upb_msgdef_addfield(m, r->f, &r->defs, NULL);
+ /* Oneof fields are added to the msgdef through their oneof, so don't need to
+ * be added here. */
+ if (upb_fielddef_containingoneof(r->f) == NULL) {
+ ok = upb_msgdef_addfield(m, r->f, &r->f, NULL);
+ UPB_ASSERT(ok);
+ }
r->f = NULL;
return true;
}
-static bool pushextension(void *closure, const void *hd) {
+static bool msg_onmapentry(void *closure, const void *hd, bool mapentry) {
upb_descreader *r = closure;
+ upb_msgdef *m = upb_descreader_top(r);
UPB_UNUSED(hd);
- assert(upb_fielddef_containingtypename(r->f));
- upb_fielddef_setisextension(r->f, true);
- upb_deflist_push(&r->defs, upb_fielddef_upcast_mutable(r->f));
+ upb_msgdef_setmapentry(m, mapentry);
r->f = NULL;
return true;
}
-#define D(name) upbdefs_google_protobuf_ ## name(s)
+
+
+/** Code to register handlers *************************************************/
+
+#define F(msg, field) upbdefs_google_protobuf_ ## msg ## _f_ ## field(m)
static void reghandlers(const void *closure, upb_handlers *h) {
- const upb_symtab *s = closure;
const upb_msgdef *m = upb_handlers_msgdef(h);
+ UPB_UNUSED(closure);
- if (m == D(DescriptorProto)) {
- upb_handlers_setstartmsg(h, &msg_startmsg, NULL);
- upb_handlers_setendmsg(h, &msg_endmsg, NULL);
- upb_handlers_setstring(h, D(DescriptorProto_name), &msg_onname, NULL);
- upb_handlers_setendsubmsg(h, D(DescriptorProto_field), &msg_onendfield,
- NULL);
- upb_handlers_setendsubmsg(h, D(DescriptorProto_extension), &pushextension,
- NULL);
- } else if (m == D(FileDescriptorProto)) {
- upb_handlers_setstartmsg(h, &file_startmsg, NULL);
- upb_handlers_setendmsg(h, &file_endmsg, NULL);
- upb_handlers_setstring(h, D(FileDescriptorProto_package), &file_onpackage,
+ if (upbdefs_google_protobuf_FileDescriptorSet_is(m)) {
+ upb_handlers_setstartsubmsg(h, F(FileDescriptorSet, file),
+ &fileset_startfile, NULL);
+ } else if (upbdefs_google_protobuf_DescriptorProto_is(m)) {
+ upb_handlers_setstartmsg(h, &msg_start, NULL);
+ upb_handlers_setendmsg(h, &msg_end, NULL);
+ upb_handlers_setstring(h, F(DescriptorProto, name), &msg_name, NULL);
+ upb_handlers_setstartsubmsg(h, F(DescriptorProto, extension), &msg_startext,
+ NULL);
+ upb_handlers_setstartsubmsg(h, F(DescriptorProto, nested_type),
+ &msg_startmsg, NULL);
+ upb_handlers_setstartsubmsg(h, F(DescriptorProto, field),
+ &msg_startfield, NULL);
+ upb_handlers_setendsubmsg(h, F(DescriptorProto, field),
+ &msg_endfield, NULL);
+ upb_handlers_setstartsubmsg(h, F(DescriptorProto, enum_type),
+ &file_startenum, NULL);
+ } else if (upbdefs_google_protobuf_FileDescriptorProto_is(m)) {
+ upb_handlers_setstartmsg(h, &file_start, NULL);
+ upb_handlers_setendmsg(h, &file_end, NULL);
+ upb_handlers_setstring(h, F(FileDescriptorProto, name), &file_onname,
+ NULL);
+ upb_handlers_setstring(h, F(FileDescriptorProto, package), &file_onpackage,
NULL);
- upb_handlers_setendsubmsg(h, D(FileDescriptorProto_extension), &pushextension,
- NULL);
- } else if (m == D(EnumValueDescriptorProto)) {
+ upb_handlers_setstring(h, F(FileDescriptorProto, syntax), &file_onsyntax,
+ NULL);
+ upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, message_type),
+ &file_startmsg, NULL);
+ upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, enum_type),
+ &file_startenum, NULL);
+ upb_handlers_setstartsubmsg(h, F(FileDescriptorProto, extension),
+ &file_startext, NULL);
+ } else if (upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)) {
upb_handlers_setstartmsg(h, &enumval_startmsg, NULL);
upb_handlers_setendmsg(h, &enumval_endmsg, NULL);
- upb_handlers_setstring(h, D(EnumValueDescriptorProto_name), &enumval_onname, NULL);
- upb_handlers_setint32(h, D(EnumValueDescriptorProto_number), &enumval_onnumber,
+ upb_handlers_setstring(h, F(EnumValueDescriptorProto, name), &enumval_onname, NULL);
+ upb_handlers_setint32(h, F(EnumValueDescriptorProto, number), &enumval_onnumber,
NULL);
- } else if (m == D(EnumDescriptorProto)) {
- upb_handlers_setstartmsg(h, &enum_startmsg, NULL);
+ } else if (upbdefs_google_protobuf_EnumDescriptorProto_is(m)) {
upb_handlers_setendmsg(h, &enum_endmsg, NULL);
- upb_handlers_setstring(h, D(EnumDescriptorProto_name), &enum_onname, NULL);
- } else if (m == D(FieldDescriptorProto)) {
+ upb_handlers_setstring(h, F(EnumDescriptorProto, name), &enum_onname, NULL);
+ } else if (upbdefs_google_protobuf_FieldDescriptorProto_is(m)) {
upb_handlers_setstartmsg(h, &field_startmsg, NULL);
upb_handlers_setendmsg(h, &field_endmsg, NULL);
- upb_handlers_setint32(h, D(FieldDescriptorProto_type), &field_ontype,
+ upb_handlers_setint32(h, F(FieldDescriptorProto, type), &field_ontype,
NULL);
- upb_handlers_setint32(h, D(FieldDescriptorProto_label), &field_onlabel,
+ upb_handlers_setint32(h, F(FieldDescriptorProto, label), &field_onlabel,
NULL);
- upb_handlers_setint32(h, D(FieldDescriptorProto_number), &field_onnumber,
+ upb_handlers_setint32(h, F(FieldDescriptorProto, number), &field_onnumber,
NULL);
- upb_handlers_setstring(h, D(FieldDescriptorProto_name), &field_onname,
+ upb_handlers_setstring(h, F(FieldDescriptorProto, name), &field_onname,
NULL);
- upb_handlers_setstring(h, D(FieldDescriptorProto_type_name),
+ upb_handlers_setstring(h, F(FieldDescriptorProto, type_name),
&field_ontypename, NULL);
- upb_handlers_setstring(h, D(FieldDescriptorProto_extendee),
+ upb_handlers_setstring(h, F(FieldDescriptorProto, extendee),
&field_onextendee, NULL);
- upb_handlers_setstring(h, D(FieldDescriptorProto_default_value),
+ upb_handlers_setstring(h, F(FieldDescriptorProto, default_value),
&field_ondefaultval, NULL);
- } else if (m == D(FieldOptions)) {
- upb_handlers_setbool(h, D(FieldOptions_lazy), &field_onlazy, NULL);
- upb_handlers_setbool(h, D(FieldOptions_packed), &field_onpacked, NULL);
+ upb_handlers_setint32(h, F(FieldDescriptorProto, oneof_index),
+ &field_ononeofindex, NULL);
+ } else if (upbdefs_google_protobuf_OneofDescriptorProto_is(m)) {
+ upb_handlers_setstring(h, F(OneofDescriptorProto, name), &oneof_name, NULL);
+ } else if (upbdefs_google_protobuf_FieldOptions_is(m)) {
+ upb_handlers_setbool(h, F(FieldOptions, lazy), &field_onlazy, NULL);
+ upb_handlers_setbool(h, F(FieldOptions, packed), &field_onpacked, NULL);
+ } else if (upbdefs_google_protobuf_MessageOptions_is(m)) {
+ upb_handlers_setbool(h, F(MessageOptions, map_entry), &msg_onmapentry, NULL);
}
+
+ UPB_ASSERT(upb_ok(upb_handlers_status(h)));
}
-#undef D
+#undef F
void descreader_cleanup(void *_r) {
upb_descreader *r = _r;
- free(r->name);
- upb_deflist_uninit(&r->defs);
- free(r->default_string);
+ size_t i;
+
+ for (i = 0; i < upb_descreader_filecount(r); i++) {
+ upb_filedef_unref(upb_descreader_file(r, i), &r->files);
+ }
+
+ upb_gfree(r->name);
+ upb_inttable_uninit(&r->files);
+ upb_inttable_uninit(&r->oneofs);
+ upb_gfree(r->default_string);
while (r->stack_len > 0) {
upb_descreader_frame *f = &r->stack[--r->stack_len];
- free(f->name);
+ upb_gfree(f->name);
}
}
@@ -6445,7 +7215,8 @@ upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
return NULL;
}
- upb_deflist_init(&r->defs);
+ upb_inttable_init(&r->files, UPB_CTYPE_PTR);
+ upb_inttable_init(&r->oneofs, UPB_CTYPE_PTR);
upb_sink_reset(upb_descreader_input(r), h, r);
r->stack_len = 0;
r->name = NULL;
@@ -6454,10 +7225,17 @@ upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h) {
return r;
}
-upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n) {
- *n = r->defs.len;
- upb_deflist_donaterefs(&r->defs, owner);
- return r->defs.defs;
+size_t upb_descreader_filecount(const upb_descreader *r) {
+ return upb_inttable_count(&r->files);
+}
+
+upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i) {
+ upb_value v;
+ if (upb_inttable_lookup(&r->files, i, &v)) {
+ return upb_value_getptr(v);
+ } else {
+ return NULL;
+ }
}
upb_sink *upb_descreader_input(upb_descreader *r) {
@@ -6465,10 +7243,9 @@ upb_sink *upb_descreader_input(upb_descreader *r) {
}
const upb_handlers *upb_descreader_newhandlers(const void *owner) {
- const upb_symtab *s = upbdefs_google_protobuf_descriptor(&s);
- const upb_handlers *h = upb_handlers_newfrozen(
- upbdefs_google_protobuf_FileDescriptorSet(s), owner, reghandlers, s);
- upb_symtab_unref(s, &s);
+ const upb_msgdef *m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
+ const upb_handlers *h = upb_handlers_newfrozen(m, owner, reghandlers, NULL);
+ upb_msgdef_unref(m, &m);
return h;
}
/*
@@ -6502,8 +7279,8 @@ static void freegroup(upb_refcounted *r) {
#ifdef UPB_USE_JIT_X64
upb_pbdecoder_freejit(g);
#endif
- free(g->bytecode);
- free(g);
+ upb_gfree(g->bytecode);
+ upb_gfree(g);
}
static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
@@ -6518,7 +7295,7 @@ static void visitgroup(const upb_refcounted *r, upb_refcounted_visit *visit,
}
mgroup *newgroup(const void *owner) {
- mgroup *g = malloc(sizeof(*g));
+ mgroup *g = upb_gmalloc(sizeof(*g));
static const struct upb_refcounted_vtbl vtbl = {visitgroup, freegroup};
upb_refcounted_init(mgroup_upcast_mutable(g), &vtbl, owner);
upb_inttable_init(&g->methods, UPB_CTYPE_PTR);
@@ -6538,7 +7315,7 @@ static void freemethod(upb_refcounted *r) {
}
upb_inttable_uninit(&method->dispatch);
- free(method);
+ upb_gfree(method);
}
static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
@@ -6550,7 +7327,7 @@ static void visitmethod(const upb_refcounted *r, upb_refcounted_visit *visit,
static upb_pbdecodermethod *newmethod(const upb_handlers *dest_handlers,
mgroup *group) {
static const struct upb_refcounted_vtbl vtbl = {visitmethod, freemethod};
- upb_pbdecodermethod *ret = malloc(sizeof(*ret));
+ upb_pbdecodermethod *ret = upb_gmalloc(sizeof(*ret));
upb_refcounted_init(upb_pbdecodermethod_upcast_mutable(ret), &vtbl, &ret);
upb_byteshandler_init(&ret->input_handler_);
@@ -6613,7 +7390,7 @@ typedef struct {
} compiler;
static compiler *newcompiler(mgroup *group, bool lazy) {
- compiler *ret = malloc(sizeof(*ret));
+ compiler *ret = upb_gmalloc(sizeof(*ret));
int i;
ret->group = group;
@@ -6626,7 +7403,7 @@ static compiler *newcompiler(mgroup *group, bool lazy) {
}
static void freecompiler(compiler *c) {
- free(c);
+ upb_gfree(c);
}
const size_t ptr_words = sizeof(void*) / sizeof(uint32_t);
@@ -6654,7 +7431,7 @@ bool op_has_longofs(int32_t instruction) {
case OP_TAGN:
return false;
default:
- assert(false);
+ UPB_ASSERT(false);
return false;
}
}
@@ -6673,7 +7450,7 @@ static void setofs(uint32_t *instruction, int32_t ofs) {
} else {
*instruction = (*instruction & ~0xff00) | ((ofs & 0xff) << 8);
}
- assert(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
+ UPB_ASSERT(getofs(*instruction) == ofs); /* Would fail in cases of overflow. */
}
static uint32_t pcofs(compiler *c) { return c->pc - c->group->bytecode; }
@@ -6685,7 +7462,7 @@ static void label(compiler *c, unsigned int label) {
int val;
uint32_t *codep;
- assert(label < MAXLABEL);
+ UPB_ASSERT(label < MAXLABEL);
val = c->fwd_labels[label];
codep = (val == EMPTYLABEL) ? NULL : c->group->bytecode + val;
while (codep) {
@@ -6706,7 +7483,7 @@ static void label(compiler *c, unsigned int label) {
* The returned value is the offset that should be written into the instruction.
*/
static int32_t labelref(compiler *c, int label) {
- assert(label < MAXLABEL);
+ UPB_ASSERT(label < MAXLABEL);
if (label == LABEL_DISPATCH) {
/* No resolving required. */
return 0;
@@ -6730,7 +7507,8 @@ static void put32(compiler *c, uint32_t v) {
size_t oldsize = g->bytecode_end - g->bytecode;
size_t newsize = UPB_MAX(oldsize * 2, 64);
/* TODO(haberman): handle OOM. */
- g->bytecode = realloc(g->bytecode, newsize * sizeof(uint32_t));
+ g->bytecode = upb_grealloc(g->bytecode, oldsize * sizeof(uint32_t),
+ newsize * sizeof(uint32_t));
g->bytecode_end = g->bytecode + newsize;
c->pc = g->bytecode + ofs;
}
@@ -6805,7 +7583,7 @@ static void putop(compiler *c, opcode op, ...) {
int label = va_arg(ap, int);
uint64_t tag = va_arg(ap, uint64_t);
uint32_t instruction = op | (tag << 16);
- assert(tag <= 0xffff);
+ UPB_ASSERT(tag <= 0xffff);
setofs(&instruction, labelref(c, label));
put32(c, instruction);
break;
@@ -6942,7 +7720,7 @@ static uint64_t get_encoded_tag(const upb_fielddef *f, int wire_type) {
uint32_t tag = (upb_fielddef_number(f) << 3) | wire_type;
uint64_t encoded_tag = upb_vencode32(tag);
/* No tag should be greater than 5 bytes. */
- assert(encoded_tag <= 0xffffffffff);
+ UPB_ASSERT(encoded_tag <= 0xffffffffff);
return encoded_tag;
}
@@ -6965,7 +7743,7 @@ static void putchecktag(compiler *c, const upb_fielddef *f,
static upb_selector_t getsel(const upb_fielddef *f, upb_handlertype_t type) {
upb_selector_t selector;
bool ok = upb_handlers_getselector(f, type, &selector);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return selector;
}
@@ -6977,7 +7755,7 @@ static uint64_t repack(uint64_t dispatch, int new_wt2) {
uint8_t wt1;
uint8_t old_wt2;
upb_pbdecoder_unpackdispatch(dispatch, &ofs, &wt1, &old_wt2);
- assert(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
+ UPB_ASSERT(old_wt2 == NO_WIRE_TYPE); /* wt2 should not be set yet. */
return upb_pbdecoder_packdispatch(ofs, wt1, new_wt2);
}
@@ -7067,7 +7845,12 @@ static void generate_msgfield(compiler *c, const upb_fielddef *f,
if (!sub_m) {
/* Don't emit any code for this field at all; it will be parsed as an
- * unknown field. */
+ * unknown field.
+ *
+ * TODO(haberman): we should change this to parse it as a string field
+ * instead. It will probably be faster, but more importantly, once we
+ * start vending unknown fields, a field shouldn't be treated as unknown
+ * just because it doesn't have subhandlers registered. */
return;
}
@@ -7174,7 +7957,7 @@ static void generate_primitivefield(compiler *c, const upb_fielddef *f,
* setting in the fielddef. This will favor (in speed) whichever was
* specified. */
- assert((int)parse_type >= 0 && parse_type <= OP_MAX);
+ UPB_ASSERT((int)parse_type >= 0 && parse_type <= OP_MAX);
sel = getsel(f, upb_handlers_getprimitivehandlertype(f));
wire_type = upb_pb_native_wire_types[upb_fielddef_descriptortype(f)];
if (upb_fielddef_isseq(f)) {
@@ -7216,7 +7999,7 @@ static void compile_method(compiler *c, upb_pbdecodermethod *method) {
upb_msg_field_iter i;
upb_value val;
- assert(method);
+ UPB_ASSERT(method);
/* Clear all entries in the dispatch table. */
upb_inttable_uninit(&method->dispatch);
@@ -7364,7 +8147,7 @@ const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
compiler *c;
UPB_UNUSED(allowjit);
- assert(upb_handlers_isfrozen(dest));
+ UPB_ASSERT(upb_handlers_isfrozen(dest));
g = newgroup(owner);
c = newcompiler(g, lazy);
@@ -7384,11 +8167,16 @@ const mgroup *mgroup_new(const upb_handlers *dest, bool allowjit, bool lazy,
#ifdef UPB_DUMP_BYTECODE
{
- FILE *f = fopen("/tmp/upb-bytecode", "wb");
- assert(f);
+ FILE *f = fopen("/tmp/upb-bytecode", "w");
+ UPB_ASSERT(f);
dumpbc(g->bytecode, g->bytecode_end, stderr);
dumpbc(g->bytecode, g->bytecode_end, f);
fclose(f);
+
+ f = fopen("/tmp/upb-bytecode.bin", "wb");
+ UPB_ASSERT(f);
+ fwrite(g->bytecode, 1, g->bytecode_end - g->bytecode, f);
+ fclose(f);
}
#endif
@@ -7436,7 +8224,7 @@ const upb_pbdecodermethod *upb_pbcodecache_getdecodermethod(
upb_inttable_push(&c->groups, upb_value_constptr(g));
ok = upb_inttable_lookupptr(&g->methods, opts->handlers, &v);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return upb_value_getptr(v);
}
@@ -7488,6 +8276,11 @@ static const char *kUnterminatedVarint = "Unterminated varint.";
static opcode halt = OP_HALT;
+/* A dummy character we can point to when the user passes us a NULL buffer.
+ * We need this because in C (NULL + 0) and (NULL - NULL) are undefined
+ * behavior, which would invalidate functions like curbufleft(). */
+static const char dummy_char;
+
/* Whether an op consumes any of the input buffer. */
static bool consumes_input(opcode op) {
switch (op) {
@@ -7564,7 +8357,7 @@ void upb_pbdecoder_seterr(upb_pbdecoder *d, const char *msg) {
/* How many bytes can be safely read from d->ptr without reading past end-of-buf
* or past the current delimited end. */
static size_t curbufleft(const upb_pbdecoder *d) {
- assert(d->data_end >= d->ptr);
+ UPB_ASSERT(d->data_end >= d->ptr);
return d->data_end - d->ptr;
}
@@ -7585,7 +8378,7 @@ size_t delim_remaining(const upb_pbdecoder *d) {
/* Advances d->ptr. */
static void advance(upb_pbdecoder *d, size_t len) {
- assert(curbufleft(d) >= len);
+ UPB_ASSERT(curbufleft(d) >= len);
d->ptr += len;
}
@@ -7618,7 +8411,7 @@ static void switchtobuf(upb_pbdecoder *d, const char *buf, const char *end) {
}
static void advancetobuf(upb_pbdecoder *d, const char *buf, size_t len) {
- assert(curbufleft(d) == 0);
+ UPB_ASSERT(curbufleft(d) == 0);
d->bufstart_ofs += (d->end - d->buf);
switchtobuf(d, buf, buf + len);
}
@@ -7627,7 +8420,7 @@ static void checkpoint(upb_pbdecoder *d) {
/* The assertion here is in the interests of efficiency, not correctness.
* We are trying to ensure that we don't checkpoint() more often than
* necessary. */
- assert(d->checkpoint != d->ptr);
+ UPB_ASSERT(d->checkpoint != d->ptr);
d->checkpoint = d->ptr;
}
@@ -7638,12 +8431,12 @@ static void checkpoint(upb_pbdecoder *d) {
* won't actually be read.
*/
static int32_t skip(upb_pbdecoder *d, size_t bytes) {
- assert(!in_residual_buf(d, d->ptr) || d->size_param == 0);
- assert(d->skip == 0);
+ UPB_ASSERT(!in_residual_buf(d, d->ptr) || d->size_param == 0);
+ UPB_ASSERT(d->skip == 0);
if (bytes > delim_remaining(d)) {
seterr(d, "Skipped value extended beyond enclosing submessage.");
return upb_pbdecoder_suspend(d);
- } else if (bufleft(d) > bytes) {
+ } else if (bufleft(d) >= bytes) {
/* Skipped data is all in current buffer, and more is still available. */
advance(d, bytes);
d->skip = 0;
@@ -7665,36 +8458,60 @@ int32_t upb_pbdecoder_resume(upb_pbdecoder *d, void *p, const char *buf,
size_t size, const upb_bufhandle *handle) {
UPB_UNUSED(p); /* Useless; just for the benefit of the JIT. */
- d->buf_param = buf;
+ /* d->skip and d->residual_end could probably elegantly be represented
+ * as a single variable, to more easily represent this invariant. */
+ UPB_ASSERT(!(d->skip && d->residual_end > d->residual));
+
+ /* We need to remember the original size_param, so that the value we return
+ * is relative to it, even if we do some skipping first. */
d->size_param = size;
d->handle = handle;
+ /* Have to handle this case specially (ie. not with skip()) because the user
+ * is allowed to pass a NULL buffer here, which won't allow us to safely
+ * calculate a d->end or use our normal functions like curbufleft(). */
+ if (d->skip && d->skip >= size) {
+ d->skip -= size;
+ d->bufstart_ofs += size;
+ buf = &dummy_char;
+ size = 0;
+
+ /* We can't just return now, because we might need to execute some ops
+ * like CHECKDELIM, which could call some callbacks and pop the stack. */
+ }
+
+ /* We need to pretend that this was the actual buffer param, since some of the
+ * calculations assume that d->ptr/d->buf is relative to this. */
+ d->buf_param = buf;
+
+ if (!buf) {
+ /* NULL buf is ok if its entire span is covered by the "skip" above, but
+ * by this point we know that "skip" doesn't cover the buffer. */
+ seterr(d, "Passed NULL buffer over non-skippable region.");
+ return upb_pbdecoder_suspend(d);
+ }
+
if (d->residual_end > d->residual) {
/* We have residual bytes from the last buffer. */
- assert(d->ptr == d->residual);
+ UPB_ASSERT(d->ptr == d->residual);
} else {
switchtobuf(d, buf, buf + size);
}
d->checkpoint = d->ptr;
+ /* Handle skips that don't cover the whole buffer (as above). */
if (d->skip) {
size_t skip_bytes = d->skip;
d->skip = 0;
CHECK_RETURN(skip(d, skip_bytes));
- d->checkpoint = d->ptr;
- }
-
- if (!buf) {
- /* NULL buf is ok if its entire span is covered by the "skip" above, but
- * by this point we know that "skip" doesn't cover the buffer. */
- seterr(d, "Passed NULL buffer over non-skippable region.");
- return upb_pbdecoder_suspend(d);
+ checkpoint(d);
}
+ /* If we're inside an unknown group, continue to parse unknown values. */
if (d->top->groupnum < 0) {
CHECK_RETURN(upb_pbdecoder_skipunknown(d, -1, 0));
- d->checkpoint = d->ptr;
+ checkpoint(d);
}
return DECODE_OK;
@@ -7709,15 +8526,14 @@ size_t upb_pbdecoder_suspend(upb_pbdecoder *d) {
d->ptr = d->residual;
return 0;
} else {
- size_t consumed;
- assert(!in_residual_buf(d, d->checkpoint));
- assert(d->buf == d->buf_param);
+ size_t ret = d->size_param - (d->end - d->checkpoint);
+ UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
+ UPB_ASSERT(d->buf == d->buf_param || d->buf == &dummy_char);
- consumed = d->checkpoint - d->buf;
- d->bufstart_ofs += consumed;
+ d->bufstart_ofs += (d->checkpoint - d->buf);
d->residual_end = d->residual;
switchtobuf(d, d->residual, d->residual_end);
- return consumed;
+ return ret;
}
}
@@ -7732,7 +8548,7 @@ static size_t suspend_save(upb_pbdecoder *d) {
if (d->checkpoint == d->residual) {
/* Checkpoint was in residual buf; append user byte(s) to residual buf. */
- assert((d->residual_end - d->residual) + d->size_param <=
+ UPB_ASSERT((d->residual_end - d->residual) + d->size_param <=
sizeof(d->residual));
if (!in_residual_buf(d, d->ptr)) {
d->bufstart_ofs -= (d->residual_end - d->residual);
@@ -7742,11 +8558,11 @@ static size_t suspend_save(upb_pbdecoder *d) {
} else {
/* Checkpoint was in user buf; old residual bytes not needed. */
size_t save;
- assert(!in_residual_buf(d, d->checkpoint));
+ UPB_ASSERT(!in_residual_buf(d, d->checkpoint));
d->ptr = d->checkpoint;
save = curbufleft(d);
- assert(save <= sizeof(d->residual));
+ UPB_ASSERT(save <= sizeof(d->residual));
memcpy(d->residual, d->ptr, save);
d->residual_end = d->residual + save;
d->bufstart_ofs = offset(d);
@@ -7760,7 +8576,7 @@ static size_t suspend_save(upb_pbdecoder *d) {
* Requires that this many bytes are available in the current buffer. */
UPB_FORCEINLINE static void consumebytes(upb_pbdecoder *d, void *buf,
size_t bytes) {
- assert(bytes <= curbufleft(d));
+ UPB_ASSERT(bytes <= curbufleft(d));
memcpy(buf, d->ptr, bytes);
advance(d, bytes);
}
@@ -7773,7 +8589,7 @@ UPB_NOINLINE static int32_t getbytes_slow(upb_pbdecoder *d, void *buf,
const size_t avail = curbufleft(d);
consumebytes(d, buf, avail);
bytes -= avail;
- assert(bytes > 0);
+ UPB_ASSERT(bytes > 0);
if (in_residual_buf(d, d->ptr)) {
advancetobuf(d, d->buf_param, d->size_param);
}
@@ -7835,8 +8651,7 @@ UPB_NOINLINE int32_t upb_pbdecoder_decode_varint_slow(upb_pbdecoder *d,
int bitpos;
*u64 = 0;
for(bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
- int32_t ret = getbytes(d, &byte, 1);
- if (ret >= 0) return ret;
+ CHECK_RETURN(getbytes(d, &byte, 1));
*u64 |= (uint64_t)(byte & 0x7F) << bitpos;
}
if(bitpos == 70 && (byte & 0x80)) {
@@ -7957,7 +8772,7 @@ UPB_NOINLINE int32_t upb_pbdecoder_checktag_slow(upb_pbdecoder *d,
if (read == bytes && data == expected) {
/* Advance past matched bytes. */
int32_t ok = getbytes(d, &data, read);
- UPB_ASSERT_VAR(ok, ok < 0);
+ UPB_ASSERT(ok < 0);
return DECODE_OK;
} else if (read < bytes && memcmp(&data, &expected, read) == 0) {
return suspend_save(d);
@@ -8032,7 +8847,7 @@ have_tag:
static void goto_endmsg(upb_pbdecoder *d) {
upb_value v;
bool found = upb_inttable_lookup32(d->top->dispatch, DISPATCH_ENDMSG, &v);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
d->pc = d->top->base + upb_value_getuint64(v);
}
@@ -8066,7 +8881,7 @@ static int32_t dispatch(upb_pbdecoder *d) {
} else if (wire_type == ((v >> 8) & 0xff)) {
bool found =
upb_inttable_lookup(dispatch, fieldnum + UPB_MAX_FIELDNUMBER, &val);
- UPB_ASSERT_VAR(found, found);
+ UPB_ASSERT(found);
d->pc = d->top->base + upb_value_getuint64(val);
return DECODE_OK;
}
@@ -8078,7 +8893,7 @@ static int32_t dispatch(upb_pbdecoder *d) {
* can re-check the delimited end. */
d->last--; /* Necessary if we get suspended */
d->pc = d->last;
- assert(getop(*d->last) == OP_CHECKDELIM);
+ UPB_ASSERT(getop(*d->last) == OP_CHECKDELIM);
/* Unknown field or ENDGROUP. */
retval = upb_pbdecoder_skipunknown(d, fieldnum, wire_type);
@@ -8096,7 +8911,7 @@ static int32_t dispatch(upb_pbdecoder *d) {
/* Callers know that the stack is more than one deep because the opcodes that
* call this only occur after PUSH operations. */
upb_pbdecoder_frame *outer_frame(upb_pbdecoder *d) {
- assert(d->top != d->stack);
+ UPB_ASSERT(d->top != d->stack);
return d->top - 1;
}
@@ -8128,7 +8943,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
op = getop(instruction);
arg = instruction >> 8;
longofs = arg;
- assert(d->ptr != d->residual_end);
+ UPB_ASSERT(d->ptr != d->residual_end);
UPB_UNUSED(group);
#ifdef UPB_DUMP_BYTECODE
fprintf(stderr, "s_ofs=%d buf_ofs=%d data_rem=%d buf_rem=%d delim_rem=%d "
@@ -8203,7 +9018,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
} else {
int32_t ret = skip(d, n);
/* This shouldn't return DECODE_OK, because n > len. */
- assert(ret >= 0);
+ UPB_ASSERT(ret >= 0);
return ret;
}
}
@@ -8225,7 +9040,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
d->top->groupnum = *d->pc++;
)
VMCASE(OP_POP,
- assert(d->top > d->stack);
+ UPB_ASSERT(d->top > d->stack);
decoder_pop(d);
)
VMCASE(OP_PUSHLENDELIM,
@@ -8241,7 +9056,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
/* We are guaranteed of this assert because we never allow ourselves to
* consume bytes beyond data_end, which covers delim_end when non-NULL.
*/
- assert(!(d->delim_end && d->ptr > d->delim_end));
+ UPB_ASSERT(!(d->delim_end && d->ptr > d->delim_end));
if (d->ptr == d->delim_end)
d->pc += longofs;
)
@@ -8250,7 +9065,7 @@ size_t run_decoder_vm(upb_pbdecoder *d, const mgroup *group,
d->pc += longofs;
)
VMCASE(OP_RET,
- assert(d->call_len > 0);
+ UPB_ASSERT(d->call_len > 0);
d->pc = d->callstack[--d->call_len];
)
VMCASE(OP_BRANCH,
@@ -8377,7 +9192,7 @@ bool upb_pbdecoder_end(void *closure, const void *handler_data) {
if (p != method->code_base.ptr) p--;
if (getop(*p) == OP_CHECKDELIM) {
/* Rewind from OP_TAG* to OP_CHECKDELIM. */
- assert(getop(*d->pc) == OP_TAG1 ||
+ UPB_ASSERT(getop(*d->pc) == OP_TAG1 ||
getop(*d->pc) == OP_TAG2 ||
getop(*d->pc) == OP_TAGN ||
getop(*d->pc) == OP_DISPATCH);
@@ -8436,11 +9251,12 @@ upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
d->env = e;
d->limit = d->stack + default_max_nesting - 1;
d->stack_size = default_max_nesting;
+ d->status = NULL;
upb_pbdecoder_reset(d);
upb_bytessink_reset(&d->input_, &m->input_handler_, d);
- assert(sink);
+ UPB_ASSERT(sink);
if (d->method_->dest_handlers_) {
if (sink->handlers != d->method_->dest_handlers_)
return NULL;
@@ -8448,7 +9264,8 @@ upb_pbdecoder *upb_pbdecoder_create(upb_env *e, const upb_pbdecodermethod *m,
upb_sink_reset(&d->top->sink, sink->handlers, sink->closure);
/* If this fails, increase the value in decoder.h. */
- assert(upb_env_bytesallocated(e) - size_before <= UPB_PB_DECODER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
+ UPB_PB_DECODER_SIZE);
return d;
}
@@ -8469,7 +9286,7 @@ size_t upb_pbdecoder_maxnesting(const upb_pbdecoder *d) {
}
bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
- assert(d->top >= d->stack);
+ UPB_ASSERT(d->top >= d->stack);
if (max < (size_t)(d->top - d->stack)) {
/* Can't set a limit smaller than what we are currently at. */
@@ -8557,7 +9374,6 @@ bool upb_pbdecoder_setmaxnesting(upb_pbdecoder *d, size_t max) {
*/
-#include <stdlib.h>
/* The output buffer is divided into segments; a segment is a string of data
* that is "ready to go" -- it does not need any varint lengths inserted into
@@ -8629,7 +9445,7 @@ struct upb_pb_encoder {
/* TODO(haberman): handle pushback */
static void putbuf(upb_pb_encoder *e, const char *buf, size_t len) {
size_t n = upb_bytessink_putbuf(e->output_, e->subc, buf, len, NULL);
- UPB_ASSERT_VAR(n, n == len);
+ UPB_ASSERT(n == len);
}
static upb_pb_encoder_segment *top(upb_pb_encoder *e) {
@@ -8669,7 +9485,7 @@ static bool reserve(upb_pb_encoder *e, size_t bytes) {
/* Call when "bytes" bytes have been writte at e->ptr. The caller *must* have
* previously called reserve() with at least this many bytes. */
static void encoder_advance(upb_pb_encoder *e, size_t bytes) {
- assert((size_t)(e->limit - e->ptr) >= bytes);
+ UPB_ASSERT((size_t)(e->limit - e->ptr) >= bytes);
e->ptr += bytes;
}
@@ -8704,7 +9520,7 @@ static bool encode_bytes(upb_pb_encoder *e, const void *data, size_t len) {
* length. */
static void accumulate(upb_pb_encoder *e) {
size_t run_len;
- assert(e->ptr >= e->runbegin);
+ UPB_ASSERT(e->ptr >= e->runbegin);
run_len = e->ptr - e->runbegin;
e->segptr->seglen += run_len;
top(e)->msglen += run_len;
@@ -8802,12 +9618,12 @@ static void new_tag(upb_handlers *h, const upb_fielddef *f, upb_wiretype_t wt,
upb_handlerattr *attr) {
uint32_t n = upb_fielddef_number(f);
- tag_t *tag = malloc(sizeof(tag_t));
+ tag_t *tag = upb_gmalloc(sizeof(tag_t));
tag->bytes = upb_vencode64((n << 3) | wt, tag->tag);
upb_handlerattr_init(attr);
upb_handlerattr_sethandlerdata(attr, tag);
- upb_handlers_addcleanup(h, tag, free);
+ upb_handlers_addcleanup(h, tag, upb_gfree);
}
static bool encode_tag(upb_pb_encoder *e, const tag_t *tag) {
@@ -9059,19 +9875,17 @@ upb_pb_encoder *upb_pb_encoder_create(upb_env *env, const upb_handlers *h,
e->ptr = e->buf;
/* If this fails, increase the value in encoder.h. */
- assert(upb_env_bytesallocated(env) - size_before <= UPB_PB_ENCODER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
+ UPB_PB_ENCODER_SIZE);
return e;
}
upb_sink *upb_pb_encoder_input(upb_pb_encoder *e) { return &e->input_; }
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
- void *owner, upb_status *status) {
+upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
+ upb_status *status) {
/* Create handlers. */
const upb_pbdecodermethod *decoder_m;
const upb_handlers *reader_h = upb_descreader_newhandlers(&reader_h);
@@ -9080,8 +9894,8 @@ upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
upb_pbdecoder *decoder;
upb_descreader *reader;
bool ok;
- upb_def **ret = NULL;
- upb_def **defs;
+ size_t i;
+ upb_filedef **ret = NULL;
upb_pbdecodermethodopts_init(&opts, reader_h);
decoder_m = upb_pbdecodermethod_new(&opts, &decoder_m);
@@ -9093,12 +9907,24 @@ upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
decoder = upb_pbdecoder_create(&env, decoder_m, upb_descreader_input(reader));
/* Push input data. */
- ok = upb_bufsrc_putbuf(str, len, upb_pbdecoder_input(decoder));
+ ok = upb_bufsrc_putbuf(buf, n, upb_pbdecoder_input(decoder));
+
+ if (!ok) {
+ goto cleanup;
+ }
+
+ ret = upb_gmalloc(sizeof (*ret) * (upb_descreader_filecount(reader) + 1));
+
+ if (!ret) {
+ goto cleanup;
+ }
- if (!ok) goto cleanup;
- defs = upb_descreader_getdefs(reader, owner, n);
- ret = malloc(sizeof(upb_def*) * (*n));
- memcpy(ret, defs, sizeof(upb_def*) * (*n));
+ for (i = 0; i < upb_descreader_filecount(reader); i++) {
+ ret[i] = upb_descreader_file(reader, i);
+ upb_filedef_ref(ret[i], owner);
+ }
+
+ ret[i] = NULL;
cleanup:
upb_env_uninit(&env);
@@ -9106,51 +9932,6 @@ cleanup:
upb_pbdecodermethod_unref(decoder_m, &decoder_m);
return ret;
}
-
-bool upb_load_descriptor_into_symtab(upb_symtab *s, const char *str, size_t len,
- upb_status *status) {
- int n;
- bool success;
- upb_def **defs = upb_load_defs_from_descriptor(str, len, &n, &defs, status);
- if (!defs) return false;
- success = upb_symtab_add(s, defs, n, &defs, status);
- free(defs);
- return success;
-}
-
-char *upb_readfile(const char *filename, size_t *len) {
- long size;
- char *buf;
- FILE *f = fopen(filename, "rb");
- if(!f) return NULL;
- if(fseek(f, 0, SEEK_END) != 0) goto error;
- size = ftell(f);
- if(size < 0) goto error;
- if(fseek(f, 0, SEEK_SET) != 0) goto error;
- buf = malloc(size + 1);
- if(size && fread(buf, size, 1, f) != 1) goto error;
- fclose(f);
- if (len) *len = size;
- return buf;
-
-error:
- fclose(f);
- return NULL;
-}
-
-bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
- upb_status *status) {
- size_t len;
- bool success;
- char *data = upb_readfile(fname, &len);
- if (!data) {
- if (status) upb_status_seterrf(status, "Couldn't read file: %s", fname);
- return false;
- }
- success = upb_load_descriptor_into_symtab(symtab, data, len, status);
- free(data);
- return success;
-}
/*
* upb::pb::TextPrinter
*
@@ -9164,7 +9945,6 @@ bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
-#include <stdlib.h>
#include <string.h>
@@ -9260,14 +10040,14 @@ bool putf(upb_textprinter *p, const char *fmt, ...) {
va_end(args_copy);
/* + 1 for NULL terminator (vsprintf() requires it even if we don't). */
- str = malloc(len + 1);
+ str = upb_gmalloc(len + 1);
if (!str) return false;
written = vsprintf(str, fmt, args);
va_end(args);
- UPB_ASSERT_VAR(written, written == len);
+ UPB_ASSERT(written == len);
ok = upb_bytessink_putbuf(p->output_, p->subc, str, len, NULL);
- free(str);
+ upb_gfree(str);
return ok;
}
@@ -9636,12 +10416,11 @@ upb_decoderet upb_vdecode_max8_wright(upb_decoderet r) {
** - handling of keys/escape-sequences/etc that span input buffers.
*/
-#include <stdio.h>
-#include <stdint.h>
#include <assert.h>
-#include <string.h>
-#include <stdlib.h>
#include <errno.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
#define UPB_JSON_MAX_DEPTH 64
@@ -9654,6 +10433,9 @@ typedef struct {
const upb_msgdef *m;
const upb_fielddef *f;
+ /* The table mapping json name to fielddef for this message. */
+ upb_strtable *name_table;
+
/* We are in a repeated-field context, ready to emit mapentries as
* submessages. This flag alters the start-of-object (open-brace) behavior to
* begin a sequence of mapentry messages rather than a single submessage. */
@@ -9674,7 +10456,7 @@ typedef struct {
struct upb_json_parser {
upb_env *env;
- upb_byteshandler input_handler_;
+ const upb_json_parsermethod *method;
upb_bytessink input_;
/* Stack to track the JSON scopes we are in. */
@@ -9709,6 +10491,19 @@ struct upb_json_parser {
uint32_t digit;
};
+struct upb_json_parsermethod {
+ upb_refcounted base;
+
+ upb_byteshandler input_handler_;
+
+ /* Mainly for the purposes of refcounting, so all the fielddefs we point
+ * to stay alive. */
+ const upb_msgdef *msg;
+
+ /* Keys are upb_msgdef*, values are upb_strtable (json_name -> fielddef) */
+ upb_inttable name_tables;
+};
+
#define PARSER_CHECK_RETURN(x) if (!(x)) return false
/* Used to signal that a capture has been suspended. */
@@ -9718,7 +10513,7 @@ static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
upb_handlertype_t type) {
upb_selector_t sel;
bool ok = upb_handlers_getselector(p->top->f, type, &sel);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return sel;
}
@@ -9737,6 +10532,13 @@ static bool check_stack(upb_json_parser *p) {
return true;
}
+static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
+ upb_value v;
+ bool ok = upb_inttable_lookupptr(&p->method->name_tables, frame->m, &v);
+ UPB_ASSERT(ok);
+ frame->name_table = upb_value_getptr(v);
+}
+
/* There are GCC/Clang built-ins for overflow checking which we could start
* using if there was any performance benefit to it. */
@@ -9856,7 +10658,7 @@ otherchar:
val = b64lookup(ptr[0]) << 18 |
b64lookup(ptr[1]) << 12;
- assert(!(val & 0x80000000));
+ UPB_ASSERT(!(val & 0x80000000));
output = val >> 16;
upb_sink_putstring(&p->top->sink, sel, &output, 1, NULL);
return true;
@@ -9910,9 +10712,8 @@ badpadding:
* the true value in a contiguous buffer. */
static void assert_accumulate_empty(upb_json_parser *p) {
- UPB_UNUSED(p);
- assert(p->accumulated == NULL);
- assert(p->accumulated_len == 0);
+ UPB_ASSERT(p->accumulated == NULL);
+ UPB_ASSERT(p->accumulated_len == 0);
}
static void accumulate_clear(upb_json_parser *p) {
@@ -9978,7 +10779,7 @@ static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
* call, and writes the length to *len. This with point either to the input
* buffer or a temporary accumulate buffer. */
static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
- assert(p->accumulated);
+ UPB_ASSERT(p->accumulated);
*len = p->accumulated_len;
return p->accumulated;
}
@@ -10016,7 +10817,7 @@ enum {
* the end. */
static void multipart_startaccum(upb_json_parser *p) {
assert_accumulate_empty(p);
- assert(p->multipart_state == MULTIPART_INACTIVE);
+ UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
p->multipart_state = MULTIPART_ACCUMULATE;
}
@@ -10024,7 +10825,7 @@ static void multipart_startaccum(upb_json_parser *p) {
* value with the given selector. */
static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
assert_accumulate_empty(p);
- assert(p->multipart_state == MULTIPART_INACTIVE);
+ UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
p->multipart_state = MULTIPART_PUSHEAGERLY;
p->string_selector = sel;
}
@@ -10057,7 +10858,7 @@ static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
/* Note: this invalidates the accumulate buffer! Call only after reading its
* contents. */
static void multipart_end(upb_json_parser *p) {
- assert(p->multipart_state != MULTIPART_INACTIVE);
+ UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
p->multipart_state = MULTIPART_INACTIVE;
accumulate_clear(p);
}
@@ -10070,13 +10871,13 @@ static void multipart_end(upb_json_parser *p) {
* region. */
static void capture_begin(upb_json_parser *p, const char *ptr) {
- assert(p->multipart_state != MULTIPART_INACTIVE);
- assert(p->capture == NULL);
+ UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
+ UPB_ASSERT(p->capture == NULL);
p->capture = ptr;
}
static bool capture_end(upb_json_parser *p, const char *ptr) {
- assert(p->capture);
+ UPB_ASSERT(p->capture);
if (multipart_text(p, p->capture, ptr - p->capture, true)) {
p->capture = NULL;
return true;
@@ -10109,7 +10910,7 @@ static void capture_suspend(upb_json_parser *p, const char **ptr) {
static void capture_resume(upb_json_parser *p, const char *ptr) {
if (p->capture) {
- assert(p->capture == &suspend_capture);
+ UPB_ASSERT(p->capture == &suspend_capture);
p->capture = ptr;
}
}
@@ -10131,7 +10932,7 @@ static char escape_char(char in) {
case '"': return '"';
case '\\': return '\\';
default:
- assert(0);
+ UPB_ASSERT(0);
return 'x';
}
}
@@ -10155,7 +10956,7 @@ static void hexdigit(upb_json_parser *p, const char *ptr) {
} else if (ch >= 'a' && ch <= 'f') {
p->digit += ((ch - 'a') + 10);
} else {
- assert(ch >= 'A' && ch <= 'F');
+ UPB_ASSERT(ch >= 'A' && ch <= 'F');
p->digit += ((ch - 'A') + 10);
}
}
@@ -10286,7 +11087,7 @@ static bool parse_number(upb_json_parser *p) {
break;
}
default:
- assert(false);
+ UPB_ASSERT(false);
}
multipart_end(p);
@@ -10312,13 +11113,13 @@ static bool parser_putbool(upb_json_parser *p, bool val) {
}
ok = upb_sink_putbool(&p->top->sink, parser_getsel(p), val);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
return true;
}
static bool start_stringval(upb_json_parser *p) {
- assert(p->top->f);
+ UPB_ASSERT(p->top->f);
if (upb_fielddef_isstring(p->top->f)) {
upb_jsonparser_frame *inner;
@@ -10333,6 +11134,7 @@ static bool start_stringval(upb_json_parser *p) {
upb_sink_startstr(&p->top->sink, sel, 0, &inner->sink);
inner->m = p->top->m;
inner->f = p->top->f;
+ inner->name_table = NULL;
inner->is_map = false;
inner->is_mapentry = false;
p->top = inner;
@@ -10379,8 +11181,8 @@ static bool end_stringval(upb_json_parser *p) {
case UPB_TYPE_STRING: {
upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
- upb_sink_endstr(&p->top->sink, sel);
p->top--;
+ upb_sink_endstr(&p->top->sink, sel);
break;
}
@@ -10407,7 +11209,7 @@ static bool end_stringval(upb_json_parser *p) {
}
default:
- assert(false);
+ UPB_ASSERT(false);
upb_status_seterrmsg(&p->status, "Internal error in JSON decoder");
upb_env_reporterror(p->env, &p->status);
ok = false;
@@ -10420,7 +11222,7 @@ static bool end_stringval(upb_json_parser *p) {
}
static void start_member(upb_json_parser *p) {
- assert(!p->top->f);
+ UPB_ASSERT(!p->top->f);
multipart_startaccum(p);
}
@@ -10478,7 +11280,7 @@ static bool parse_mapentry_key(upb_json_parser *p) {
sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
upb_sink_putstring(&subsink, sel, buf, len, NULL);
sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
- upb_sink_endstr(&subsink, sel);
+ upb_sink_endstr(&p->top->sink, sel);
multipart_end(p);
break;
}
@@ -10519,6 +11321,7 @@ static bool handle_mapentry(upb_json_parser *p) {
sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
inner->m = mapentrymsg;
+ inner->name_table = NULL;
inner->mapfield = mapfield;
inner->is_map = false;
@@ -10548,27 +11351,27 @@ static bool handle_mapentry(upb_json_parser *p) {
}
static bool end_membername(upb_json_parser *p) {
- assert(!p->top->f);
+ UPB_ASSERT(!p->top->f);
if (p->top->is_map) {
return handle_mapentry(p);
} else {
size_t len;
const char *buf = accumulate_getptr(p, &len);
- const upb_fielddef *f = upb_msgdef_ntof(p->top->m, buf, len);
+ upb_value v;
+
+ if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
+ p->top->f = upb_value_getconstptr(v);
+ multipart_end(p);
- if (!f) {
+ return true;
+ } else {
/* TODO(haberman): Ignore unknown fields if requested/configured to do
* so. */
upb_status_seterrf(&p->status, "No such field: %.*s\n", (int)len, buf);
upb_env_reporterror(p->env, &p->status);
return false;
}
-
- p->top->f = f;
- multipart_end(p);
-
- return true;
}
}
@@ -10580,7 +11383,7 @@ static void end_member(upb_json_parser *p) {
bool ok;
const upb_fielddef *mapfield;
- assert(p->top > p->stack);
+ UPB_ASSERT(p->top > p->stack);
/* send ENDMSG on submsg. */
upb_sink_endmsg(&p->top->sink, &s);
mapfield = p->top->mapfield;
@@ -10588,7 +11391,7 @@ static void end_member(upb_json_parser *p) {
/* send ENDSUBMSG in repeated-field-of-mapentries frame. */
p->top--;
ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
upb_sink_endsubmsg(&p->top->sink, sel);
}
@@ -10596,7 +11399,7 @@ static void end_member(upb_json_parser *p) {
}
static bool start_subobject(upb_json_parser *p) {
- assert(p->top->f);
+ UPB_ASSERT(p->top->f);
if (upb_fielddef_ismap(p->top->f)) {
upb_jsonparser_frame *inner;
@@ -10610,6 +11413,7 @@ static bool start_subobject(upb_json_parser *p) {
sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
upb_sink_startseq(&p->top->sink, sel, &inner->sink);
inner->m = upb_fielddef_msgsubdef(p->top->f);
+ inner->name_table = NULL;
inner->mapfield = p->top->f;
inner->f = NULL;
inner->is_map = true;
@@ -10630,6 +11434,7 @@ static bool start_subobject(upb_json_parser *p) {
sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
upb_sink_startsubmsg(&p->top->sink, sel, &inner->sink);
inner->m = upb_fielddef_msgsubdef(p->top->f);
+ set_name_table(p, inner);
inner->f = NULL;
inner->is_map = false;
inner->is_mapentry = false;
@@ -10663,7 +11468,7 @@ static bool start_array(upb_json_parser *p) {
upb_jsonparser_frame *inner;
upb_selector_t sel;
- assert(p->top->f);
+ UPB_ASSERT(p->top->f);
if (!upb_fielddef_isseq(p->top->f)) {
upb_status_seterrf(&p->status,
@@ -10679,6 +11484,7 @@ static bool start_array(upb_json_parser *p) {
sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
upb_sink_startseq(&p->top->sink, sel, &inner->sink);
inner->m = p->top->m;
+ inner->name_table = NULL;
inner->f = p->top->f;
inner->is_map = false;
inner->is_mapentry = false;
@@ -10690,7 +11496,7 @@ static bool start_array(upb_json_parser *p) {
static void end_array(upb_json_parser *p) {
upb_selector_t sel;
- assert(p->top > p->stack);
+ UPB_ASSERT(p->top > p->stack);
p->top--;
sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
@@ -10736,11 +11542,11 @@ static void end_object(upb_json_parser *p) {
* final state once, when the closing '"' is seen. */
-#line 1218 "upb/json/parser.rl"
+#line 1244 "upb/json/parser.rl"
-#line 1130 "upb/json/parser.c"
+#line 1156 "upb/json/parser.c"
static const char _json_actions[] = {
0, 1, 0, 1, 2, 1, 3, 1,
5, 1, 6, 1, 7, 1, 8, 1,
@@ -10889,7 +11695,7 @@ static const int json_en_value_machine = 27;
static const int json_en_main = 1;
-#line 1221 "upb/json/parser.rl"
+#line 1247 "upb/json/parser.rl"
size_t parse(void *closure, const void *hd, const char *buf, size_t size,
const upb_bufhandle *handle) {
@@ -10911,7 +11717,7 @@ size_t parse(void *closure, const void *hd, const char *buf, size_t size,
capture_resume(parser, buf);
-#line 1301 "upb/json/parser.c"
+#line 1327 "upb/json/parser.c"
{
int _klen;
unsigned int _trans;
@@ -10986,118 +11792,118 @@ _match:
switch ( *_acts++ )
{
case 0:
-#line 1133 "upb/json/parser.rl"
+#line 1159 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 1:
-#line 1134 "upb/json/parser.rl"
+#line 1160 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 10; goto _again;} }
break;
case 2:
-#line 1138 "upb/json/parser.rl"
+#line 1164 "upb/json/parser.rl"
{ start_text(parser, p); }
break;
case 3:
-#line 1139 "upb/json/parser.rl"
+#line 1165 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_text(parser, p)); }
break;
case 4:
-#line 1145 "upb/json/parser.rl"
+#line 1171 "upb/json/parser.rl"
{ start_hex(parser); }
break;
case 5:
-#line 1146 "upb/json/parser.rl"
+#line 1172 "upb/json/parser.rl"
{ hexdigit(parser, p); }
break;
case 6:
-#line 1147 "upb/json/parser.rl"
+#line 1173 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_hex(parser)); }
break;
case 7:
-#line 1153 "upb/json/parser.rl"
+#line 1179 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(escape(parser, p)); }
break;
case 8:
-#line 1159 "upb/json/parser.rl"
+#line 1185 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
case 9:
-#line 1162 "upb/json/parser.rl"
+#line 1188 "upb/json/parser.rl"
{ {stack[top++] = cs; cs = 19; goto _again;} }
break;
case 10:
-#line 1164 "upb/json/parser.rl"
+#line 1190 "upb/json/parser.rl"
{ p--; {stack[top++] = cs; cs = 27; goto _again;} }
break;
case 11:
-#line 1169 "upb/json/parser.rl"
+#line 1195 "upb/json/parser.rl"
{ start_member(parser); }
break;
case 12:
-#line 1170 "upb/json/parser.rl"
+#line 1196 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_membername(parser)); }
break;
case 13:
-#line 1173 "upb/json/parser.rl"
+#line 1199 "upb/json/parser.rl"
{ end_member(parser); }
break;
case 14:
-#line 1179 "upb/json/parser.rl"
+#line 1205 "upb/json/parser.rl"
{ start_object(parser); }
break;
case 15:
-#line 1182 "upb/json/parser.rl"
+#line 1208 "upb/json/parser.rl"
{ end_object(parser); }
break;
case 16:
-#line 1188 "upb/json/parser.rl"
+#line 1214 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_array(parser)); }
break;
case 17:
-#line 1192 "upb/json/parser.rl"
+#line 1218 "upb/json/parser.rl"
{ end_array(parser); }
break;
case 18:
-#line 1197 "upb/json/parser.rl"
+#line 1223 "upb/json/parser.rl"
{ start_number(parser, p); }
break;
case 19:
-#line 1198 "upb/json/parser.rl"
+#line 1224 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_number(parser, p)); }
break;
case 20:
-#line 1200 "upb/json/parser.rl"
+#line 1226 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_stringval(parser)); }
break;
case 21:
-#line 1201 "upb/json/parser.rl"
+#line 1227 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(end_stringval(parser)); }
break;
case 22:
-#line 1203 "upb/json/parser.rl"
+#line 1229 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(parser_putbool(parser, true)); }
break;
case 23:
-#line 1205 "upb/json/parser.rl"
+#line 1231 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(parser_putbool(parser, false)); }
break;
case 24:
-#line 1207 "upb/json/parser.rl"
+#line 1233 "upb/json/parser.rl"
{ /* null value */ }
break;
case 25:
-#line 1209 "upb/json/parser.rl"
+#line 1235 "upb/json/parser.rl"
{ CHECK_RETURN_TOP(start_subobject(parser)); }
break;
case 26:
-#line 1210 "upb/json/parser.rl"
+#line 1236 "upb/json/parser.rl"
{ end_subobject(parser); }
break;
case 27:
-#line 1215 "upb/json/parser.rl"
+#line 1241 "upb/json/parser.rl"
{ p--; {cs = stack[--top]; goto _again;} }
break;
-#line 1487 "upb/json/parser.c"
+#line 1513 "upb/json/parser.c"
}
}
@@ -11110,10 +11916,10 @@ _again:
_out: {}
}
-#line 1242 "upb/json/parser.rl"
+#line 1268 "upb/json/parser.rl"
if (p != pe) {
- upb_status_seterrf(&parser->status, "Parse error at %s\n", p);
+ upb_status_seterrf(&parser->status, "Parse error at '%.*s'\n", pe - p, p);
upb_env_reporterror(parser->env, &parser->status);
} else {
capture_suspend(parser, &p);
@@ -11151,13 +11957,13 @@ static void json_parser_reset(upb_json_parser *p) {
/* Emit Ragel initialization of the parser. */
-#line 1541 "upb/json/parser.c"
+#line 1567 "upb/json/parser.c"
{
cs = json_start;
top = 0;
}
-#line 1282 "upb/json/parser.rl"
+#line 1308 "upb/json/parser.rl"
p->current_state = cs;
p->parser_top = top;
accumulate_clear(p);
@@ -11167,10 +11973,84 @@ static void json_parser_reset(upb_json_parser *p) {
upb_status_clear(&p->status);
}
+static void visit_json_parsermethod(const upb_refcounted *r,
+ upb_refcounted_visit *visit,
+ void *closure) {
+ const upb_json_parsermethod *method = (upb_json_parsermethod*)r;
+ visit(r, upb_msgdef_upcast2(method->msg), closure);
+}
+
+static void free_json_parsermethod(upb_refcounted *r) {
+ upb_json_parsermethod *method = (upb_json_parsermethod*)r;
+
+ upb_inttable_iter i;
+ upb_inttable_begin(&i, &method->name_tables);
+ for(; !upb_inttable_done(&i); upb_inttable_next(&i)) {
+ upb_value val = upb_inttable_iter_value(&i);
+ upb_strtable *t = upb_value_getptr(val);
+ upb_strtable_uninit(t);
+ upb_gfree(t);
+ }
+
+ upb_inttable_uninit(&method->name_tables);
+
+ upb_gfree(r);
+}
+
+static void add_jsonname_table(upb_json_parsermethod *m, const upb_msgdef* md) {
+ upb_msg_field_iter i;
+ upb_strtable *t;
+
+ /* It would be nice to stack-allocate this, but protobufs do not limit the
+ * length of fields to any reasonable limit. */
+ char *buf = NULL;
+ size_t len = 0;
+
+ if (upb_inttable_lookupptr(&m->name_tables, md, NULL)) {
+ return;
+ }
+
+ /* TODO(haberman): handle malloc failure. */
+ t = upb_gmalloc(sizeof(*t));
+ upb_strtable_init(t, UPB_CTYPE_CONSTPTR);
+ upb_inttable_insertptr(&m->name_tables, md, upb_value_ptr(t));
+
+ for(upb_msg_field_begin(&i, md);
+ !upb_msg_field_done(&i);
+ upb_msg_field_next(&i)) {
+ const upb_fielddef *f = upb_msg_iter_field(&i);
+
+ /* Add an entry for the JSON name. */
+ size_t field_len = upb_fielddef_getjsonname(f, buf, len);
+ if (field_len > len) {
+ size_t len2;
+ buf = upb_grealloc(buf, 0, field_len);
+ len = field_len;
+ len2 = upb_fielddef_getjsonname(f, buf, len);
+ UPB_ASSERT(len == len2);
+ }
+ upb_strtable_insert(t, buf, upb_value_constptr(f));
+
+ if (strcmp(buf, upb_fielddef_name(f)) != 0) {
+ /* Since the JSON name is different from the regular field name, add an
+ * entry for the raw name (compliant proto3 JSON parsers must accept
+ * both). */
+ upb_strtable_insert(t, upb_fielddef_name(f), upb_value_constptr(f));
+ }
+
+ if (upb_fielddef_issubmsg(f)) {
+ add_jsonname_table(m, upb_fielddef_msgsubdef(f));
+ }
+ }
+
+ upb_gfree(buf);
+}
/* Public API *****************************************************************/
-upb_json_parser *upb_json_parser_create(upb_env *env, upb_sink *output) {
+upb_json_parser *upb_json_parser_create(upb_env *env,
+ const upb_json_parsermethod *method,
+ upb_sink *output) {
#ifndef NDEBUG
const size_t size_before = upb_env_bytesallocated(env);
#endif
@@ -11178,35 +12058,59 @@ upb_json_parser *upb_json_parser_create(upb_env *env, upb_sink *output) {
if (!p) return false;
p->env = env;
+ p->method = method;
p->limit = p->stack + UPB_JSON_MAX_DEPTH;
p->accumulate_buf = NULL;
p->accumulate_buf_size = 0;
- upb_byteshandler_init(&p->input_handler_);
- upb_byteshandler_setstring(&p->input_handler_, parse, NULL);
- upb_byteshandler_setendstr(&p->input_handler_, end, NULL);
- upb_bytessink_reset(&p->input_, &p->input_handler_, p);
+ upb_bytessink_reset(&p->input_, &method->input_handler_, p);
json_parser_reset(p);
upb_sink_reset(&p->top->sink, output->handlers, output->closure);
p->top->m = upb_handlers_msgdef(output->handlers);
+ set_name_table(p, p->top);
/* If this fails, uncomment and increase the value in parser.h. */
/* fprintf(stderr, "%zd\n", upb_env_bytesallocated(env) - size_before); */
- assert(upb_env_bytesallocated(env) - size_before <= UPB_JSON_PARSER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(env) - size_before <=
+ UPB_JSON_PARSER_SIZE);
return p;
}
upb_bytessink *upb_json_parser_input(upb_json_parser *p) {
return &p->input_;
}
+
+upb_json_parsermethod *upb_json_parsermethod_new(const upb_msgdef* md,
+ const void* owner) {
+ static const struct upb_refcounted_vtbl vtbl = {visit_json_parsermethod,
+ free_json_parsermethod};
+ upb_json_parsermethod *ret = upb_gmalloc(sizeof(*ret));
+ upb_refcounted_init(upb_json_parsermethod_upcast_mutable(ret), &vtbl, owner);
+
+ ret->msg = md;
+ upb_ref2(md, ret);
+
+ upb_byteshandler_init(&ret->input_handler_);
+ upb_byteshandler_setstring(&ret->input_handler_, parse, ret);
+ upb_byteshandler_setendstr(&ret->input_handler_, end, ret);
+
+ upb_inttable_init(&ret->name_tables, UPB_CTYPE_PTR);
+
+ add_jsonname_table(ret, md);
+
+ return ret;
+}
+
+const upb_byteshandler *upb_json_parsermethod_inputhandler(
+ const upb_json_parsermethod *m) {
+ return &m->input_handler_;
+}
/*
** This currently uses snprintf() to format primitives, and could be optimized
** further.
*/
-#include <stdlib.h>
-#include <stdio.h>
#include <string.h>
#include <stdint.h>
@@ -11233,15 +12137,34 @@ struct upb_json_printer {
/* StringPiece; a pointer plus a length. */
typedef struct {
- const char *ptr;
+ char *ptr;
size_t len;
} strpc;
-strpc *newstrpc(upb_handlers *h, const upb_fielddef *f) {
- strpc *ret = malloc(sizeof(*ret));
- ret->ptr = upb_fielddef_name(f);
- ret->len = strlen(ret->ptr);
- upb_handlers_addcleanup(h, ret, free);
+void freestrpc(void *ptr) {
+ strpc *pc = ptr;
+ upb_gfree(pc->ptr);
+ upb_gfree(pc);
+}
+
+/* Convert fielddef name to JSON name and return as a string piece. */
+strpc *newstrpc(upb_handlers *h, const upb_fielddef *f,
+ bool preserve_fieldnames) {
+ /* TODO(haberman): handle malloc failure. */
+ strpc *ret = upb_gmalloc(sizeof(*ret));
+ if (preserve_fieldnames) {
+ ret->ptr = upb_gstrdup(upb_fielddef_name(f));
+ ret->len = strlen(ret->ptr);
+ } else {
+ size_t len;
+ ret->len = upb_fielddef_getjsonname(f, NULL, 0);
+ ret->ptr = upb_gmalloc(ret->len);
+ len = upb_fielddef_getjsonname(f, ret->ptr, ret->len);
+ UPB_ASSERT(len == ret->len);
+ ret->len--; /* NULL */
+ }
+
+ upb_handlers_addcleanup(h, ret, freestrpc);
return ret;
}
@@ -11251,7 +12174,7 @@ static void print_data(
upb_json_printer *p, const char *buf, unsigned int len) {
/* TODO: Will need to change if we support pushback from the sink. */
size_t n = upb_bytessink_putbuf(p->output_, p->subc_, buf, len, NULL);
- UPB_ASSERT_VAR(n, n == len);
+ UPB_ASSERT(n == len);
}
static void print_comma(upb_json_printer *p) {
@@ -11272,7 +12195,7 @@ UPB_INLINE bool is_json_escaped(char c) {
return uc < kControlCharLimit || uc == '"' || uc == '\\';
}
-UPB_INLINE char* json_nice_escape(char c) {
+UPB_INLINE const char* json_nice_escape(char c) {
switch (c) {
case '"': return "\\\"";
case '\\': return "\\\\";
@@ -11601,7 +12524,7 @@ static size_t putbytes(void *closure, const void *handler_data, const char *str,
while (remaining > 2) {
/* TODO(haberman): handle encoded lengths > sizeof(data) */
- UPB_ASSERT_VAR(limit, (limit - to) >= 4);
+ UPB_ASSERT((limit - to) >= 4);
to[0] = base64[from[0] >> 2];
to[1] = base64[((from[0] & 0x3) << 4) | (from[1] >> 4)];
@@ -11745,11 +12668,12 @@ static size_t mapkey_bytes(void *closure, const void *handler_data,
static void set_enum_hd(upb_handlers *h,
const upb_fielddef *f,
+ bool preserve_fieldnames,
upb_handlerattr *attr) {
- EnumHandlerData *hd = malloc(sizeof(EnumHandlerData));
+ EnumHandlerData *hd = upb_gmalloc(sizeof(EnumHandlerData));
hd->enumdef = (const upb_enumdef *)upb_fielddef_subdef(f);
- hd->keyname = newstrpc(h, f);
- upb_handlers_addcleanup(h, hd, free);
+ hd->keyname = newstrpc(h, f, preserve_fieldnames);
+ upb_handlers_addcleanup(h, hd, upb_gfree);
upb_handlerattr_sethandlerdata(attr, hd);
}
@@ -11765,7 +12689,8 @@ static void set_enum_hd(upb_handlers *h,
* our sources that emit mapentry messages do so canonically (with one key
* field, and then one value field), so this is not a pressing concern at the
* moment. */
-void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
+void printer_sethandlers_mapentry(const void *closure, bool preserve_fieldnames,
+ upb_handlers *h) {
const upb_msgdef *md = upb_handlers_msgdef(h);
/* A mapentry message is printed simply as '"key": value'. Rather than
@@ -11803,7 +12728,7 @@ void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
upb_handlers_setstring(h, key_field, mapkey_bytes, &empty_attr);
break;
default:
- assert(false);
+ UPB_ASSERT(false);
break;
}
@@ -11839,7 +12764,7 @@ void printer_sethandlers_mapentry(const void *closure, upb_handlers *h) {
break;
case UPB_TYPE_ENUM: {
upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
- set_enum_hd(h, value_field, &enum_attr);
+ set_enum_hd(h, value_field, preserve_fieldnames, &enum_attr);
upb_handlers_setint32(h, value_field, mapvalue_enum, &enum_attr);
upb_handlerattr_uninit(&enum_attr);
break;
@@ -11858,13 +12783,13 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
bool is_mapentry = upb_msgdef_mapentry(md);
upb_handlerattr empty_attr = UPB_HANDLERATTR_INITIALIZER;
upb_msg_field_iter i;
-
- UPB_UNUSED(closure);
+ const bool *preserve_fieldnames_ptr = closure;
+ const bool preserve_fieldnames = *preserve_fieldnames_ptr;
if (is_mapentry) {
/* mapentry messages are sufficiently different that we handle them
* separately. */
- printer_sethandlers_mapentry(closure, h);
+ printer_sethandlers_mapentry(closure, preserve_fieldnames, h);
return;
}
@@ -11885,7 +12810,8 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
const upb_fielddef *f = upb_msg_iter_field(&i);
upb_handlerattr name_attr = UPB_HANDLERATTR_INITIALIZER;
- upb_handlerattr_sethandlerdata(&name_attr, newstrpc(h, f));
+ upb_handlerattr_sethandlerdata(&name_attr,
+ newstrpc(h, f, preserve_fieldnames));
if (upb_fielddef_ismap(f)) {
upb_handlers_setstartseq(h, f, startmap, &name_attr);
@@ -11908,7 +12834,7 @@ void printer_sethandlers(const void *closure, upb_handlers *h) {
* option later to control this behavior, but we will wait for a real
* need first. */
upb_handlerattr enum_attr = UPB_HANDLERATTR_INITIALIZER;
- set_enum_hd(h, f, &enum_attr);
+ set_enum_hd(h, f, preserve_fieldnames, &enum_attr);
if (upb_fielddef_isseq(f)) {
upb_handlers_setint32(h, f, repeated_enum, &enum_attr);
@@ -11976,7 +12902,8 @@ upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
upb_sink_reset(&p->input_, h, p);
/* If this fails, increase the value in printer.h. */
- assert(upb_env_bytesallocated(e) - size_before <= UPB_JSON_PRINTER_SIZE);
+ UPB_ASSERT_DEBUGVAR(upb_env_bytesallocated(e) - size_before <=
+ UPB_JSON_PRINTER_SIZE);
return p;
}
@@ -11985,6 +12912,8 @@ upb_sink *upb_json_printer_input(upb_json_printer *p) {
}
const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
+ bool preserve_fieldnames,
const void *owner) {
- return upb_handlers_newfrozen(md, owner, printer_sethandlers, NULL);
+ return upb_handlers_newfrozen(
+ md, owner, printer_sethandlers, &preserve_fieldnames);
}
diff --git a/php/ext/google/protobuf/upb.h b/php/ext/google/protobuf/upb.h
index 073faf41..c83b0e03 100644
--- a/php/ext/google/protobuf/upb.h
+++ b/php/ext/google/protobuf/upb.h
@@ -5,6 +5,7 @@
**
** - 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.
@@ -54,14 +55,19 @@
** store pointers or integers of at least 32 bits (upb isn't really useful on
** systems where sizeof(void*) < 4).
**
-** The table must be homogeneous (all values of the same type). In debug
+** 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 <assert.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 <stdint.h>
#include <string.h>
/*
@@ -79,6 +85,18 @@
#include <stdbool.h>
#include <stddef.h>
+#ifdef __cplusplus
+namespace upb {
+class Allocator;
+class Arena;
+class Environment;
+class ErrorSpace;
+class Status;
+template <int N> class InlinedArena;
+template <int N> class InlinedEnvironment;
+}
+#endif
+
/* UPB_INLINE: inline if possible, emit standalone code if required. */
#ifdef __cplusplus
#define UPB_INLINE inline
@@ -146,6 +164,7 @@
#define UPB_ASSERT_STDLAYOUT(type) \
static_assert(std::is_standard_layout<type>::value, \
#type " must be standard layout");
+#define UPB_FINAL final
#else /* !defined(UPB_CXX11) */
#define UPB_DISALLOW_COPY_AND_ASSIGN(class_name) \
class_name(const class_name&); \
@@ -155,6 +174,7 @@
~class_name(); \
UPB_DISALLOW_COPY_AND_ASSIGN(class_name)
#define UPB_ASSERT_STDLAYOUT(type)
+#define UPB_FINAL
#endif
/* UPB_DECLARE_TYPE()
@@ -193,13 +213,15 @@
template <> \
class Pointer<cppname> : public PointerBase<cppname, cppbase> { \
public: \
- explicit Pointer(cppname* ptr) : PointerBase(ptr) {} \
+ explicit Pointer(cppname* ptr) \
+ : PointerBase<cppname, cppbase>(ptr) {} \
}; \
template <> \
class Pointer<const cppname> \
: public PointerBase<const cppname, const cppbase> { \
public: \
- explicit Pointer(const cppname* ptr) : PointerBase(ptr) {} \
+ explicit Pointer(const cppname* ptr) \
+ : PointerBase<const cppname, const cppbase>(ptr) {} \
}; \
}
@@ -211,13 +233,15 @@
template <> \
class Pointer<cppname> : public PointerBase2<cppname, cppbase, cppbase2> { \
public: \
- explicit Pointer(cppname* ptr) : PointerBase2(ptr) {} \
+ explicit Pointer(cppname* ptr) \
+ : PointerBase2<cppname, cppbase, cppbase2>(ptr) {} \
}; \
template <> \
class Pointer<const cppname> \
: public PointerBase2<const cppname, const cppbase, const cppbase2> { \
public: \
- explicit Pointer(const cppname* ptr) : PointerBase2(ptr) {} \
+ explicit Pointer(const cppname* ptr) \
+ : PointerBase2<const cppname, const cppbase, const cppbase2>(ptr) {} \
}; \
}
@@ -244,14 +268,22 @@
#define UPB_UNUSED(var) (void)var
-/* For asserting something about a variable when the variable is not used for
- * anything else. This prevents "unused variable" warnings when compiling in
- * debug mode. */
-#define UPB_ASSERT_VAR(var, predicate) UPB_UNUSED(var); assert(predicate)
+/* UPB_ASSERT(): in release mode, we use the expression without letting it be
+ * evaluated. This prevents "unused variable" warnings. */
+#ifdef NDEBUG
+#define UPB_ASSERT(expr) do {} while (false && (expr))
+#else
+#define UPB_ASSERT(expr) assert(expr)
+#endif
+
+/* UPB_ASSERT_DEBUGVAR(): assert that uses functions or variables that only
+ * exist in debug mode. This turns into regular assert. */
+#define UPB_ASSERT_DEBUGVAR(expr) assert(expr)
/* Generic function type. */
typedef void upb_func();
+
/* C++ Casts ******************************************************************/
#ifdef __cplusplus
@@ -329,243 +361,430 @@ class PointerBase2 : public PointerBase<T, Base> {
#endif
-/* upb::reffed_ptr ************************************************************/
+/* upb::ErrorSpace ************************************************************/
+
+/* A upb::ErrorSpace represents some domain of possible error values. This lets
+ * upb::Status attach specific error codes to operations, like POSIX/C errno,
+ * Win32 error codes, etc. Clients who want to know the very specific error
+ * code can check the error space and then know the type of the integer code.
+ *
+ * NOTE: upb::ErrorSpace is currently not used and should be considered
+ * experimental. It is important primarily in cases where upb is performing
+ * I/O, but upb doesn't currently have any components that do this. */
+
+UPB_DECLARE_TYPE(upb::ErrorSpace, upb_errorspace)
#ifdef __cplusplus
+class upb::ErrorSpace {
+#else
+struct upb_errorspace {
+#endif
+ const char *name;
+};
-#include <algorithm> /* For std::swap(). */
-namespace upb {
+/* upb::Status ****************************************************************/
-/* Provides RAII semantics for upb refcounted objects. Each reffed_ptr owns a
- * ref on whatever object it points to (if any). */
-template <class T> class reffed_ptr {
+/* upb::Status represents a success or failure status and error message.
+ * It owns no resources and allocates no memory, so it should work
+ * even in OOM situations. */
+UPB_DECLARE_TYPE(upb::Status, upb_status)
+
+/* The maximum length of an error message before it will get truncated. */
+#define UPB_STATUS_MAX_MESSAGE 128
+
+UPB_BEGIN_EXTERN_C
+
+const char *upb_status_errmsg(const upb_status *status);
+bool upb_ok(const upb_status *status);
+upb_errorspace *upb_status_errspace(const upb_status *status);
+int upb_status_errcode(const upb_status *status);
+
+/* Any of the functions that write to a status object allow status to be NULL,
+ * to support use cases where the function's caller does not care about the
+ * status message. */
+void upb_status_clear(upb_status *status);
+void upb_status_seterrmsg(upb_status *status, const char *msg);
+void upb_status_seterrf(upb_status *status, const char *fmt, ...);
+void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args);
+void upb_status_copy(upb_status *to, const upb_status *from);
+
+UPB_END_EXTERN_C
+
+#ifdef __cplusplus
+
+class upb::Status {
public:
- reffed_ptr() : ptr_(NULL) {}
+ Status() { upb_status_clear(this); }
- /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */
- template <class U>
- reffed_ptr(U* val, const void* ref_donor = NULL)
- : ptr_(upb::upcast(val)) {
- if (ref_donor) {
- assert(ptr_);
- ptr_->DonateRef(ref_donor, this);
- } else if (ptr_) {
- ptr_->Ref(this);
- }
- }
+ /* Returns true if there is no error. */
+ bool ok() const { return upb_ok(this); }
- template <class U>
- reffed_ptr(const reffed_ptr<U>& other)
- : ptr_(upb::upcast(other.get())) {
- if (ptr_) ptr_->Ref(this);
- }
+ /* Optional error space and code, useful if the caller wants to
+ * programmatically check the specific kind of error. */
+ ErrorSpace* error_space() { return upb_status_errspace(this); }
+ int error_code() const { return upb_status_errcode(this); }
- ~reffed_ptr() { if (ptr_) ptr_->Unref(this); }
+ /* The returned string is invalidated by any other call into the status. */
+ const char *error_message() const { return upb_status_errmsg(this); }
- template <class U>
- reffed_ptr& operator=(const reffed_ptr<U>& other) {
- reset(other.get());
- return *this;
+ /* The error message will be truncated if it is longer than
+ * UPB_STATUS_MAX_MESSAGE-4. */
+ void SetErrorMessage(const char* msg) { upb_status_seterrmsg(this, msg); }
+ void SetFormattedErrorMessage(const char* fmt, ...) {
+ va_list args;
+ va_start(args, fmt);
+ upb_status_vseterrf(this, fmt, args);
+ va_end(args);
}
- reffed_ptr& operator=(const reffed_ptr& other) {
- reset(other.get());
- return *this;
- }
+ /* Resets the status to a successful state with no message. */
+ void Clear() { upb_status_clear(this); }
- /* TODO(haberman): add C++11 move construction/assignment for greater
- * efficiency. */
+ void CopyFrom(const Status& other) { upb_status_copy(this, &other); }
- void swap(reffed_ptr& other) {
- if (ptr_ == other.ptr_) {
- return;
- }
+ private:
+ UPB_DISALLOW_COPY_AND_ASSIGN(Status)
+#else
+struct upb_status {
+#endif
+ bool ok_;
- if (ptr_) ptr_->DonateRef(this, &other);
- if (other.ptr_) other.ptr_->DonateRef(&other, this);
- std::swap(ptr_, other.ptr_);
- }
+ /* Specific status code defined by some error space (optional). */
+ int code_;
+ upb_errorspace *error_space_;
- T& operator*() const {
- assert(ptr_);
- return *ptr_;
- }
+ /* TODO(haberman): add file/line of error? */
- T* operator->() const {
- assert(ptr_);
- return ptr_;
- }
+ /* Error message; NULL-terminated. */
+ char msg[UPB_STATUS_MAX_MESSAGE];
+};
- T* get() const { return ptr_; }
+#define UPB_STATUS_INIT {true, 0, NULL, {0}}
- /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */
- template <class U>
- void reset(U* ptr = NULL, const void* ref_donor = NULL) {
- reffed_ptr(ptr, ref_donor).swap(*this);
- }
- template <class U>
- reffed_ptr<U> down_cast() {
- return reffed_ptr<U>(upb::down_cast<U*>(get()));
- }
+/** Built-in error spaces. ****************************************************/
- template <class U>
- reffed_ptr<U> dyn_cast() {
- return reffed_ptr<U>(upb::dyn_cast<U*>(get()));
- }
+/* Errors raised by upb that we want to be able to detect programmatically. */
+typedef enum {
+ UPB_NOMEM /* Can't reuse ENOMEM because it is POSIX, not ISO C. */
+} upb_errcode_t;
- /* Plain release() is unsafe; if we were the only owner, it would leak the
- * object. Instead we provide this: */
- T* ReleaseTo(const void* new_owner) {
- T* ret = NULL;
- ptr_->DonateRef(this, new_owner);
- std::swap(ret, ptr_);
- return ret;
- }
+extern upb_errorspace upb_upberr;
+
+void upb_upberr_setoom(upb_status *s);
+
+/* Since errno is defined by standard C, we define an error space for it in
+ * core upb. Other error spaces should be defined in other, platform-specific
+ * modules. */
+
+extern upb_errorspace upb_errnoerr;
+
+
+/** upb::Allocator ************************************************************/
+
+/* A upb::Allocator is a possibly-stateful allocator object.
+ *
+ * It could either be an arena allocator (which doesn't require individual
+ * free() calls) or a regular malloc() (which does). The client must therefore
+ * free memory unless it knows that the allocator is an arena allocator. */
+UPB_DECLARE_TYPE(upb::Allocator, upb_alloc)
+
+/* A malloc()/free() function.
+ * If "size" is 0 then the function acts like free(), otherwise it acts like
+ * realloc(). Only "oldsize" bytes from a previous allocation are preserved. */
+typedef void *upb_alloc_func(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size);
+
+#ifdef __cplusplus
+
+class upb::Allocator UPB_FINAL {
+ public:
+ Allocator() {}
private:
- T* ptr_;
+ UPB_DISALLOW_COPY_AND_ASSIGN(Allocator)
+
+ public:
+#else
+struct upb_alloc {
+#endif /* __cplusplus */
+ upb_alloc_func *func;
};
-} /* namespace upb */
+UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) {
+ UPB_ASSERT(size > 0);
+ return alloc->func(alloc, NULL, 0, size);
+}
-#endif /* __cplusplus */
+UPB_INLINE void *upb_realloc(upb_alloc *alloc, void *ptr, size_t oldsize,
+ size_t size) {
+ UPB_ASSERT(size > 0);
+ return alloc->func(alloc, ptr, oldsize, size);
+}
+UPB_INLINE void upb_free(upb_alloc *alloc, void *ptr) {
+ alloc->func(alloc, ptr, 0, 0);
+}
-/* upb::Status ****************************************************************/
+/* The global allocator used by upb. Uses the standard malloc()/free(). */
-#ifdef __cplusplus
-namespace upb {
-class ErrorSpace;
-class Status;
+extern upb_alloc upb_alloc_global;
+
+/* Functions that hard-code the global malloc.
+ *
+ * We still get benefit because we can put custom logic into our global
+ * allocator, like injecting out-of-memory faults in debug/testing builds. */
+
+UPB_INLINE void *upb_gmalloc(size_t size) {
+ return upb_malloc(&upb_alloc_global, size);
}
-#endif
-UPB_DECLARE_TYPE(upb::ErrorSpace, upb_errorspace)
-UPB_DECLARE_TYPE(upb::Status, upb_status)
+UPB_INLINE void *upb_grealloc(void *ptr, size_t oldsize, size_t size) {
+ return upb_realloc(&upb_alloc_global, ptr, oldsize, size);
+}
-/* The maximum length of an error message before it will get truncated. */
-#define UPB_STATUS_MAX_MESSAGE 128
+UPB_INLINE void upb_gfree(void *ptr) {
+ upb_free(&upb_alloc_global, ptr);
+}
-/* An error callback function is used to report errors from some component.
- * The function can return "true" to indicate that the component should try
- * to recover and proceed, but this is not always possible. */
-typedef bool upb_errcb_t(void *closure, const upb_status* status);
+/* upb::Arena *****************************************************************/
+
+/* upb::Arena is a specific allocator implementation that uses arena allocation.
+ * The user provides an allocator that will be used to allocate the underlying
+ * arena blocks. Arenas by nature do not require the individual allocations
+ * to be freed. However the Arena does allow users to register cleanup
+ * functions that will run when the arena is destroyed.
+ *
+ * A upb::Arena is *not* thread-safe.
+ *
+ * You could write a thread-safe arena allocator that satisfies the
+ * upb::Allocator interface, but it would not be as efficient for the
+ * single-threaded case. */
+UPB_DECLARE_TYPE(upb::Arena, upb_arena)
+
+typedef void upb_cleanup_func(void *ud);
+
+#define UPB_ARENA_BLOCK_OVERHEAD (sizeof(size_t)*4)
+
+UPB_BEGIN_EXTERN_C
+
+void upb_arena_init(upb_arena *a);
+void upb_arena_init2(upb_arena *a, void *mem, size_t n, upb_alloc *alloc);
+void upb_arena_uninit(upb_arena *a);
+upb_alloc *upb_arena_alloc(upb_arena *a);
+bool upb_arena_addcleanup(upb_arena *a, upb_cleanup_func *func, void *ud);
+size_t upb_arena_bytesallocated(const upb_arena *a);
+void upb_arena_setnextblocksize(upb_arena *a, size_t size);
+void upb_arena_setmaxblocksize(upb_arena *a, size_t size);
+
+UPB_END_EXTERN_C
#ifdef __cplusplus
-class upb::ErrorSpace {
+
+class upb::Arena {
+ public:
+ /* A simple arena with no initial memory block and the default allocator. */
+ Arena() { upb_arena_init(this); }
+
+ /* Constructs an arena with the given initial block which allocates blocks
+ * with the given allocator. The given allocator must outlive the Arena.
+ *
+ * If you pass NULL for the allocator it will default to the global allocator
+ * upb_alloc_global, and NULL/0 for the initial block will cause there to be
+ * no initial block. */
+ Arena(void *mem, size_t len, Allocator* a) {
+ upb_arena_init2(this, mem, len, a);
+ }
+
+ ~Arena() { upb_arena_uninit(this); }
+
+ /* Sets the size of the next block the Arena will request (unless the
+ * requested allocation is larger). Each block will double in size until the
+ * max limit is reached. */
+ void SetNextBlockSize(size_t size) { upb_arena_setnextblocksize(this, size); }
+
+ /* Sets the maximum block size. No blocks larger than this will be requested
+ * from the underlying allocator unless individual arena allocations are
+ * larger. */
+ void SetMaxBlockSize(size_t size) { upb_arena_setmaxblocksize(this, size); }
+
+ /* Allows this arena to be used as a generic allocator.
+ *
+ * The arena does not need free() calls so when using Arena as an allocator
+ * it is safe to skip them. However they are no-ops so there is no harm in
+ * calling free() either. */
+ Allocator* allocator() { return upb_arena_alloc(this); }
+
+ /* Add a cleanup function to run when the arena is destroyed.
+ * Returns false on out-of-memory. */
+ bool AddCleanup(upb_cleanup_func* func, void* ud) {
+ return upb_arena_addcleanup(this, func, ud);
+ }
+
+ /* Total number of bytes that have been allocated. It is undefined what
+ * Realloc() does to this counter. */
+ size_t BytesAllocated() const {
+ return upb_arena_bytesallocated(this);
+ }
+
+ private:
+ UPB_DISALLOW_COPY_AND_ASSIGN(Arena)
+
#else
-struct upb_errorspace {
-#endif
- const char *name;
- /* Should the error message in the status object according to this code. */
- void (*set_message)(upb_status* status, int code);
+struct upb_arena {
+#endif /* __cplusplus */
+ /* We implement the allocator interface.
+ * This must be the first member of upb_arena! */
+ upb_alloc alloc;
+
+ /* Allocator to allocate arena blocks. We are responsible for freeing these
+ * when we are destroyed. */
+ upb_alloc *block_alloc;
+
+ size_t bytes_allocated;
+ size_t next_block_size;
+ size_t max_block_size;
+
+ /* Linked list of blocks. Points to an arena_block, defined in env.c */
+ void *block_head;
+
+ /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
+ void *cleanup_head;
+
+ /* For future expansion, since the size of this struct is exposed to users. */
+ void *future1;
+ void *future2;
};
-#ifdef __cplusplus
-/* Object representing a success or failure status.
- * It owns no resources and allocates no memory, so it should work
- * even in OOM situations. */
+/* upb::Environment ***********************************************************/
-class upb::Status {
- public:
- Status();
+/* A upb::Environment provides a means for injecting malloc and an
+ * error-reporting callback into encoders/decoders. This allows them to be
+ * independent of nearly all assumptions about their actual environment.
+ *
+ * It is also a container for allocating the encoders/decoders themselves that
+ * insulates clients from knowing their actual size. This provides ABI
+ * compatibility even if the size of the objects change. And this allows the
+ * structure definitions to be in the .c files instead of the .h files, making
+ * the .h files smaller and more readable.
+ *
+ * We might want to consider renaming this to "Pipeline" if/when the concept of
+ * a pipeline element becomes more formalized. */
+UPB_DECLARE_TYPE(upb::Environment, upb_env)
- /* Returns true if there is no error. */
- bool ok() const;
+/* A function that receives an error report from an encoder or decoder. The
+ * callback can return true to request that the error should be recovered, but
+ * if the error is not recoverable this has no effect. */
+typedef bool upb_error_func(void *ud, const upb_status *status);
- /* Optional error space and code, useful if the caller wants to
- * programmatically check the specific kind of error. */
- ErrorSpace* error_space();
- int code() const;
+UPB_BEGIN_EXTERN_C
- const char *error_message() const;
+void upb_env_init(upb_env *e);
+void upb_env_init2(upb_env *e, void *mem, size_t n, upb_alloc *alloc);
+void upb_env_uninit(upb_env *e);
- /* The error message will be truncated if it is longer than
- * UPB_STATUS_MAX_MESSAGE-4. */
- void SetErrorMessage(const char* msg);
- void SetFormattedErrorMessage(const char* fmt, ...);
+void upb_env_initonly(upb_env *e);
- /* If there is no error message already, this will use the ErrorSpace to
- * populate the error message for this code. The caller can still call
- * SetErrorMessage() to give a more specific message. */
- void SetErrorCode(ErrorSpace* space, int code);
+upb_arena *upb_env_arena(upb_env *e);
+bool upb_env_ok(const upb_env *e);
+void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud);
- /* Resets the status to a successful state with no message. */
- void Clear();
+/* Convenience wrappers around the methods of the contained arena. */
+void upb_env_reporterrorsto(upb_env *e, upb_status *s);
+bool upb_env_reporterror(upb_env *e, const upb_status *s);
+void *upb_env_malloc(upb_env *e, size_t size);
+void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size);
+void upb_env_free(upb_env *e, void *ptr);
+bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud);
+size_t upb_env_bytesallocated(const upb_env *e);
- void CopyFrom(const Status& other);
+UPB_END_EXTERN_C
+
+#ifdef __cplusplus
+
+class upb::Environment {
+ public:
+ /* The given Arena must outlive this environment. */
+ Environment() { upb_env_initonly(this); }
+
+ Environment(void *mem, size_t len, Allocator *a) : arena_(mem, len, a) {
+ upb_env_initonly(this);
+ }
+
+ Arena* arena() { return upb_env_arena(this); }
+
+ /* Set a custom error reporting function. */
+ void SetErrorFunction(upb_error_func* func, void* ud) {
+ upb_env_seterrorfunc(this, func, ud);
+ }
+
+ /* Set the error reporting function to simply copy the status to the given
+ * status and abort. */
+ void ReportErrorsTo(Status* status) { upb_env_reporterrorsto(this, status); }
+
+ /* Returns true if all allocations and AddCleanup() calls have succeeded,
+ * and no errors were reported with ReportError() (except ones that recovered
+ * successfully). */
+ bool ok() const { return upb_env_ok(this); }
+
+ /* Reports an error to this environment's callback, returning true if
+ * the caller should try to recover. */
+ bool ReportError(const Status* status) {
+ return upb_env_reporterror(this, status);
+ }
private:
- UPB_DISALLOW_COPY_AND_ASSIGN(Status)
+ UPB_DISALLOW_COPY_AND_ASSIGN(Environment)
+
#else
-struct upb_status {
-#endif
+struct upb_env {
+#endif /* __cplusplus */
+ upb_arena arena_;
+ upb_error_func *error_func_;
+ void *error_ud_;
bool ok_;
+};
- /* Specific status code defined by some error space (optional). */
- int code_;
- upb_errorspace *error_space_;
- /* Error message; NULL-terminated. */
- char msg[UPB_STATUS_MAX_MESSAGE];
-};
+/* upb::InlinedArena **********************************************************/
+/* upb::InlinedEnvironment ****************************************************/
-#define UPB_STATUS_INIT {true, 0, NULL, {0}}
+/* upb::InlinedArena and upb::InlinedEnvironment seed their arenas with a
+ * predefined amount of memory. No heap memory will be allocated until the
+ * initial block is exceeded.
+ *
+ * These types only exist in C++ */
#ifdef __cplusplus
-extern "C" {
-#endif
-/* The returned string is invalidated by any other call into the status. */
-const char *upb_status_errmsg(const upb_status *status);
-bool upb_ok(const upb_status *status);
-upb_errorspace *upb_status_errspace(const upb_status *status);
-int upb_status_errcode(const upb_status *status);
+template <int N> class upb::InlinedArena : public upb::Arena {
+ public:
+ InlinedArena() : Arena(initial_block_, N, NULL) {}
+ explicit InlinedArena(Allocator* a) : Arena(initial_block_, N, a) {}
-/* Any of the functions that write to a status object allow status to be NULL,
- * to support use cases where the function's caller does not care about the
- * status message. */
-void upb_status_clear(upb_status *status);
-void upb_status_seterrmsg(upb_status *status, const char *msg);
-void upb_status_seterrf(upb_status *status, const char *fmt, ...);
-void upb_status_vseterrf(upb_status *status, const char *fmt, va_list args);
-void upb_status_seterrcode(upb_status *status, upb_errorspace *space, int code);
-void upb_status_copy(upb_status *to, const upb_status *from);
+ private:
+ UPB_DISALLOW_COPY_AND_ASSIGN(InlinedArena)
-#ifdef __cplusplus
-} /* extern "C" */
+ char initial_block_[N + UPB_ARENA_BLOCK_OVERHEAD];
+};
-namespace upb {
+template <int N> class upb::InlinedEnvironment : public upb::Environment {
+ public:
+ InlinedEnvironment() : Environment(initial_block_, N, NULL) {}
+ explicit InlinedEnvironment(Allocator *a)
+ : Environment(initial_block_, N, a) {}
-/* C++ Wrappers */
-inline Status::Status() { Clear(); }
-inline bool Status::ok() const { return upb_ok(this); }
-inline const char* Status::error_message() const {
- return upb_status_errmsg(this);
-}
-inline void Status::SetErrorMessage(const char* msg) {
- upb_status_seterrmsg(this, msg);
-}
-inline void Status::SetFormattedErrorMessage(const char* fmt, ...) {
- va_list args;
- va_start(args, fmt);
- upb_status_vseterrf(this, fmt, args);
- va_end(args);
-}
-inline void Status::SetErrorCode(ErrorSpace* space, int code) {
- upb_status_seterrcode(this, space, code);
-}
-inline void Status::Clear() { upb_status_clear(this); }
-inline void Status::CopyFrom(const Status& other) {
- upb_status_copy(this, &other);
-}
+ private:
+ UPB_DISALLOW_COPY_AND_ASSIGN(InlinedEnvironment)
+
+ char initial_block_[N + UPB_ARENA_BLOCK_OVERHEAD];
+};
+
+#endif /* __cplusplus */
-} /* namespace upb */
-#endif
#endif /* UPB_H_ */
@@ -607,10 +826,14 @@ typedef struct {
#endif
/* Like strdup(), which isn't always available since it's not ANSI C. */
-char *upb_strdup(const char *s);
+char *upb_strdup(const char *s, upb_alloc *a);
/* Variant that works with a length-delimited rather than NULL-delimited string,
* as supported by strtable. */
-char *upb_strdup2(const char *s, size_t len);
+char *upb_strdup2(const char *s, size_t len, upb_alloc *a);
+
+UPB_INLINE char *upb_gstrdup(const char *s) {
+ return upb_strdup(s, &upb_alloc_global);
+}
UPB_INLINE void _upb_value_setval(upb_value *v, uint64_t val,
upb_ctype_t ctype) {
@@ -643,7 +866,7 @@ UPB_INLINE upb_value _upb_value_val(uint64_t val, upb_ctype_t ctype) {
return ret; \
} \
UPB_INLINE type_t upb_value_get ## name(upb_value val) { \
- assert(val.ctype == proto_type); \
+ UPB_ASSERT_DEBUGVAR(val.ctype == proto_type); \
return (type_t)(converter)val.val; \
}
@@ -787,14 +1010,40 @@ typedef struct {
* initialize const hash tables. Then we cast away const when we have to.
*/
const upb_tabent *entries;
+
+#ifndef NDEBUG
+ /* This table's allocator. We make the user pass it in to every relevant
+ * function and only use this to check it in debug mode. We do this solely
+ * to keep upb_table as small as possible. This might seem slightly paranoid
+ * but the plan is to use upb_table for all map fields and extension sets in
+ * a forthcoming message representation, so there could be a lot of these.
+ * If this turns out to be too annoying later, we can change it (since this
+ * is an internal-only header file). */
+ upb_alloc *alloc;
+#endif
} upb_table;
+#ifdef NDEBUG
+# define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \
+ {count, mask, ctype, size_lg2, entries}
+#else
+# ifdef UPB_DEBUG_REFS
+/* At the moment the only mutable tables we statically initialize are debug
+ * ref tables. */
+# define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \
+ {count, mask, ctype, size_lg2, entries, &upb_alloc_debugrefs}
+# else
+# define UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries) \
+ {count, mask, ctype, size_lg2, entries, NULL}
+# endif
+#endif
+
typedef struct {
upb_table t;
} upb_strtable;
#define UPB_STRTABLE_INIT(count, mask, ctype, size_lg2, entries) \
- {{count, mask, ctype, size_lg2, entries}}
+ {UPB_TABLE_INIT(count, mask, ctype, size_lg2, entries)}
#define UPB_EMPTY_STRTABLE_INIT(ctype) \
UPB_STRTABLE_INIT(0, 0, ctype, 0, NULL)
@@ -807,7 +1056,7 @@ typedef struct {
} upb_inttable;
#define UPB_INTTABLE_INIT(count, mask, ctype, size_lg2, ent, a, asize, acount) \
- {{count, mask, ctype, size_lg2, ent}, a, asize, acount}
+ {UPB_TABLE_INIT(count, mask, ctype, size_lg2, ent), a, asize, acount}
#define UPB_EMPTY_INTTABLE_INIT(ctype) \
UPB_INTTABLE_INIT(0, 0, ctype, 0, NULL, NULL, 0, 0)
@@ -847,10 +1096,26 @@ UPB_INLINE bool upb_arrhas(upb_tabval key) {
/* Initialize and uninitialize a table, respectively. If memory allocation
* failed, false is returned that the table is uninitialized. */
-bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype);
-bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype);
-void upb_inttable_uninit(upb_inttable *table);
-void upb_strtable_uninit(upb_strtable *table);
+bool upb_inttable_init2(upb_inttable *table, upb_ctype_t ctype, upb_alloc *a);
+bool upb_strtable_init2(upb_strtable *table, upb_ctype_t ctype, upb_alloc *a);
+void upb_inttable_uninit2(upb_inttable *table, upb_alloc *a);
+void upb_strtable_uninit2(upb_strtable *table, upb_alloc *a);
+
+UPB_INLINE bool upb_inttable_init(upb_inttable *table, upb_ctype_t ctype) {
+ return upb_inttable_init2(table, ctype, &upb_alloc_global);
+}
+
+UPB_INLINE bool upb_strtable_init(upb_strtable *table, upb_ctype_t ctype) {
+ return upb_strtable_init2(table, ctype, &upb_alloc_global);
+}
+
+UPB_INLINE void upb_inttable_uninit(upb_inttable *table) {
+ upb_inttable_uninit2(table, &upb_alloc_global);
+}
+
+UPB_INLINE void upb_strtable_uninit(upb_strtable *table) {
+ upb_strtable_uninit2(table, &upb_alloc_global);
+}
/* Returns the number of values in the table. */
size_t upb_inttable_count(const upb_inttable *t);
@@ -865,9 +1130,20 @@ UPB_INLINE size_t upb_strtable_count(const upb_strtable *t) {
*
* If a table resize was required but memory allocation failed, false is
* returned and the table is unchanged. */
-bool upb_inttable_insert(upb_inttable *t, uintptr_t key, upb_value val);
-bool upb_strtable_insert2(upb_strtable *t, const char *key, size_t len,
- upb_value val);
+bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
+ upb_alloc *a);
+bool upb_strtable_insert3(upb_strtable *t, const char *key, size_t len,
+ upb_value val, upb_alloc *a);
+
+UPB_INLINE bool upb_inttable_insert(upb_inttable *t, uintptr_t key,
+ upb_value val) {
+ return upb_inttable_insert2(t, key, val, &upb_alloc_global);
+}
+
+UPB_INLINE bool upb_strtable_insert2(upb_strtable *t, const char *key,
+ size_t len, upb_value val) {
+ return upb_strtable_insert3(t, key, len, val, &upb_alloc_global);
+}
/* For NULL-terminated strings. */
UPB_INLINE bool upb_strtable_insert(upb_strtable *t, const char *key,
@@ -890,8 +1166,13 @@ UPB_INLINE bool upb_strtable_lookup(const upb_strtable *t, const char *key,
/* Removes an item from the table. Returns true if the remove was successful,
* and stores the removed item in *val if non-NULL. */
bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val);
-bool upb_strtable_remove2(upb_strtable *t, const char *key, size_t len,
- upb_value *val);
+bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
+ upb_value *val, upb_alloc *alloc);
+
+UPB_INLINE bool upb_strtable_remove2(upb_strtable *t, const char *key,
+ size_t len, upb_value *val) {
+ return upb_strtable_remove3(t, key, len, val, &upb_alloc_global);
+}
/* For NULL-terminated strings. */
UPB_INLINE bool upb_strtable_remove(upb_strtable *t, const char *key,
@@ -906,19 +1187,33 @@ bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val);
/* Handy routines for treating an inttable like a stack. May not be mixed with
* other insert/remove calls. */
-bool upb_inttable_push(upb_inttable *t, upb_value val);
+bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a);
upb_value upb_inttable_pop(upb_inttable *t);
+UPB_INLINE bool upb_inttable_push(upb_inttable *t, upb_value val) {
+ return upb_inttable_push2(t, val, &upb_alloc_global);
+}
+
/* Convenience routines for inttables with pointer keys. */
-bool upb_inttable_insertptr(upb_inttable *t, const void *key, upb_value val);
+bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
+ upb_alloc *a);
bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val);
bool upb_inttable_lookupptr(
const upb_inttable *t, const void *key, upb_value *val);
+UPB_INLINE bool upb_inttable_insertptr(upb_inttable *t, const void *key,
+ upb_value val) {
+ return upb_inttable_insertptr2(t, key, val, &upb_alloc_global);
+}
+
/* Optimizes the table for the current set of entries, for both memory use and
* lookup time. Client should call this after all entries have been inserted;
* inserting more entries is legal, but will likely require a table resize. */
-void upb_inttable_compact(upb_inttable *t);
+void upb_inttable_compact2(upb_inttable *t, upb_alloc *a);
+
+UPB_INLINE void upb_inttable_compact(upb_inttable *t) {
+ upb_inttable_compact2(t, &upb_alloc_global);
+}
/* A special-case inlinable version of the lookup routine for 32-bit
* integers. */
@@ -947,7 +1242,7 @@ UPB_INLINE bool upb_inttable_lookup32(const upb_inttable *t, uint32_t key,
}
/* Exposed for testing only. */
-bool upb_strtable_resize(upb_strtable *t, size_t size_lg2);
+bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a);
/* Iterators ******************************************************************/
@@ -992,8 +1287,8 @@ typedef struct {
void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t);
void upb_strtable_next(upb_strtable_iter *i);
bool upb_strtable_done(const upb_strtable_iter *i);
-const char *upb_strtable_iter_key(upb_strtable_iter *i);
-size_t upb_strtable_iter_keylength(upb_strtable_iter *i);
+const char *upb_strtable_iter_key(const upb_strtable_iter *i);
+size_t upb_strtable_iter_keylength(const upb_strtable_iter *i);
upb_value upb_strtable_iter_value(const upb_strtable_iter *i);
void upb_strtable_iter_setdone(upb_strtable_iter *i);
bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
@@ -1046,7 +1341,10 @@ bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
/* #define UPB_DEBUG_REFS */
#ifdef __cplusplus
-namespace upb { class RefCounted; }
+namespace upb {
+class RefCounted;
+template <class T> class reffed_ptr;
+}
#endif
UPB_DECLARE_TYPE(upb::RefCounted, upb_refcounted)
@@ -1114,10 +1412,12 @@ struct upb_refcounted {
};
#ifdef UPB_DEBUG_REFS
-#define UPB_REFCOUNT_INIT(refs, ref2s) \
- {&static_refcount, NULL, NULL, 0, true, refs, ref2s}
+extern upb_alloc upb_alloc_debugrefs;
+#define UPB_REFCOUNT_INIT(vtbl, refs, ref2s) \
+ {&static_refcount, NULL, vtbl, 0, true, refs, ref2s}
#else
-#define UPB_REFCOUNT_INIT(refs, ref2s) {&static_refcount, NULL, NULL, 0, true}
+#define UPB_REFCOUNT_INIT(vtbl, refs, ref2s) \
+ {&static_refcount, NULL, vtbl, 0, true}
#endif
UPB_BEGIN_EXTERN_C
@@ -1250,6 +1550,111 @@ inline void RefCounted::CheckRef(const void *owner) const {
} /* namespace upb */
#endif
+
+/* upb::reffed_ptr ************************************************************/
+
+#ifdef __cplusplus
+
+#include <algorithm> /* For std::swap(). */
+
+/* Provides RAII semantics for upb refcounted objects. Each reffed_ptr owns a
+ * ref on whatever object it points to (if any). */
+template <class T> class upb::reffed_ptr {
+ public:
+ reffed_ptr() : ptr_(NULL) {}
+
+ /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */
+ template <class U>
+ reffed_ptr(U* val, const void* ref_donor = NULL)
+ : ptr_(upb::upcast(val)) {
+ if (ref_donor) {
+ UPB_ASSERT(ptr_);
+ ptr_->DonateRef(ref_donor, this);
+ } else if (ptr_) {
+ ptr_->Ref(this);
+ }
+ }
+
+ template <class U>
+ reffed_ptr(const reffed_ptr<U>& other)
+ : ptr_(upb::upcast(other.get())) {
+ if (ptr_) ptr_->Ref(this);
+ }
+
+ reffed_ptr(const reffed_ptr& other)
+ : ptr_(upb::upcast(other.get())) {
+ if (ptr_) ptr_->Ref(this);
+ }
+
+ ~reffed_ptr() { if (ptr_) ptr_->Unref(this); }
+
+ template <class U>
+ reffed_ptr& operator=(const reffed_ptr<U>& other) {
+ reset(other.get());
+ return *this;
+ }
+
+ reffed_ptr& operator=(const reffed_ptr& other) {
+ reset(other.get());
+ return *this;
+ }
+
+ /* TODO(haberman): add C++11 move construction/assignment for greater
+ * efficiency. */
+
+ void swap(reffed_ptr& other) {
+ if (ptr_ == other.ptr_) {
+ return;
+ }
+
+ if (ptr_) ptr_->DonateRef(this, &other);
+ if (other.ptr_) other.ptr_->DonateRef(&other, this);
+ std::swap(ptr_, other.ptr_);
+ }
+
+ T& operator*() const {
+ UPB_ASSERT(ptr_);
+ return *ptr_;
+ }
+
+ T* operator->() const {
+ UPB_ASSERT(ptr_);
+ return ptr_;
+ }
+
+ T* get() const { return ptr_; }
+
+ /* If ref_donor is NULL, takes a new ref, otherwise adopts from ref_donor. */
+ template <class U>
+ void reset(U* ptr = NULL, const void* ref_donor = NULL) {
+ reffed_ptr(ptr, ref_donor).swap(*this);
+ }
+
+ template <class U>
+ reffed_ptr<U> down_cast() {
+ return reffed_ptr<U>(upb::down_cast<U*>(get()));
+ }
+
+ template <class U>
+ reffed_ptr<U> dyn_cast() {
+ return reffed_ptr<U>(upb::dyn_cast<U*>(get()));
+ }
+
+ /* Plain release() is unsafe; if we were the only owner, it would leak the
+ * object. Instead we provide this: */
+ T* ReleaseTo(const void* new_owner) {
+ T* ret = NULL;
+ ptr_->DonateRef(this, new_owner);
+ std::swap(ret, ptr_);
+ return ret;
+ }
+
+ private:
+ T* ptr_;
+};
+
+#endif /* __cplusplus */
+
#endif /* UPB_REFCOUNT_H_ */
#ifdef __cplusplus
@@ -1261,12 +1666,17 @@ namespace upb {
class Def;
class EnumDef;
class FieldDef;
+class FileDef;
class MessageDef;
class OneofDef;
}
#endif
UPB_DECLARE_DERIVED_TYPE(upb::Def, upb::RefCounted, upb_def, upb_refcounted)
+UPB_DECLARE_DERIVED_TYPE(upb::OneofDef, upb::RefCounted, upb_oneofdef,
+ upb_refcounted)
+UPB_DECLARE_DERIVED_TYPE(upb::FileDef, upb::RefCounted, upb_filedef,
+ upb_refcounted)
/* The maximum message depth that the type graph can have. This is a resource
* limit for the C stack since we sometimes need to recursively traverse the
@@ -1278,15 +1688,16 @@ UPB_DECLARE_DERIVED_TYPE(upb::Def, upb::RefCounted, upb_def, upb_refcounted)
#define UPB_MAX_MESSAGE_DEPTH 64
-/* upb::Def: base class for defs *********************************************/
+/* upb::Def: base class for top-level defs ***********************************/
-/* All the different kind of defs we support. These correspond 1:1 with
- * declarations in a .proto file. */
+/* All the different kind of defs that can be defined at the top-level and put
+ * in a SymbolTable or appear in a FileDef::defs() list. This excludes some
+ * defs (like oneofs and files). It only includes fields because they can be
+ * defined as extensions. */
typedef enum {
UPB_DEF_MSG,
UPB_DEF_FIELD,
UPB_DEF_ENUM,
- UPB_DEF_ONEOF,
UPB_DEF_SERVICE, /* Not yet implemented. */
UPB_DEF_ANY = -1 /* Wildcard for upb_symtab_get*() */
} upb_deftype_t;
@@ -1309,6 +1720,9 @@ class upb::Def {
/* "fullname" is the def's fully-qualified name (eg. foo.bar.Message). */
const char *full_name() const;
+ /* The final part of a def's name (eg. Message). */
+ const char *name() const;
+
/* The def must be mutable. Caller retains ownership of fullname. Defs are
* not required to have a name; if a def has no name when it is frozen, it
* will remain an anonymous def. On failure, returns false and details in "s"
@@ -1316,6 +1730,11 @@ class upb::Def {
bool set_full_name(const char* fullname, upb::Status* s);
bool set_full_name(const std::string &fullname, upb::Status* s);
+ /* The file in which this def appears. It is not necessary to add a def to a
+ * file (and consequently the accessor may return NULL). Set this by calling
+ * file->Add(def). */
+ FileDef* file() const;
+
/* Freezes the given defs; this validates all constraints and marks the defs
* as frozen (read-only). "defs" may not contain any fielddefs, but fields
* of any msgdefs will be frozen.
@@ -1327,7 +1746,7 @@ class upb::Def {
*
* After this operation succeeds, the finalized defs must only be accessed
* through a const pointer! */
- static bool Freeze(Def* const* defs, int n, Status* status);
+ static bool Freeze(Def* const* defs, size_t n, Status* status);
static bool Freeze(const std::vector<Def*>& defs, Status* status);
private:
@@ -1346,8 +1765,13 @@ UPB_REFCOUNTED_CMETHODS(upb_def, upb_def_upcast)
upb_deftype_t upb_def_type(const upb_def *d);
const char *upb_def_fullname(const upb_def *d);
+const char *upb_def_name(const upb_def *d);
+const upb_filedef *upb_def_file(const upb_def *d);
bool upb_def_setfullname(upb_def *def, const char *fullname, upb_status *s);
-bool upb_def_freeze(upb_def *const *defs, int n, upb_status *s);
+bool upb_def_freeze(upb_def *const *defs, size_t n, upb_status *s);
+
+/* Temporary API: for internal use only. */
+bool _upb_def_validate(upb_def *const*defs, size_t n, upb_status *s);
UPB_END_EXTERN_C
@@ -1396,7 +1820,7 @@ UPB_END_EXTERN_C
return (upb_##lower *)def; \
} \
UPB_INLINE const upb_##lower *upb_downcast_##lower(const upb_def *def) { \
- assert(upb_def_type(def) == UPB_DEF_##upper); \
+ UPB_ASSERT(upb_def_type(def) == UPB_DEF_##upper); \
return (const upb_##lower *)def; \
} \
UPB_INLINE upb_##lower *upb_dyncast_##lower##_mutable(upb_def *def) { \
@@ -1420,7 +1844,6 @@ UPB_END_EXTERN_C
UPB_DECLARE_DEF_TYPE(upb::FieldDef, fielddef, FIELD)
UPB_DECLARE_DEF_TYPE(upb::MessageDef, msgdef, MSG)
UPB_DECLARE_DEF_TYPE(upb::EnumDef, enumdef, ENUM)
-UPB_DECLARE_DEF_TYPE(upb::OneofDef, oneofdef, ONEOF)
#undef UPB_DECLARE_DEF_TYPE
#undef UPB_DEF_CASTS
@@ -1483,6 +1906,11 @@ typedef enum {
UPB_DESCRIPTOR_TYPE_SINT64 = 18
} upb_descriptortype_t;
+typedef enum {
+ UPB_SYNTAX_PROTO2 = 2,
+ UPB_SYNTAX_PROTO3 = 3
+} upb_syntax_t;
+
/* Maximum field number allowed for FieldDefs. This is an inherent limit of the
* protobuf wire format. */
#define UPB_MAX_FIELDNUMBER ((1 << 29) - 1)
@@ -1537,6 +1965,27 @@ class upb::FieldDef {
uint32_t number() const; /* Returns 0 if uninitialized. */
bool is_extension() const;
+ /* Copies the JSON name for this field into the given buffer. Returns the
+ * actual size of the JSON name, including the NULL terminator. If the
+ * return value is 0, the JSON name is unset. If the return value is
+ * greater than len, the JSON name was truncated. The buffer is always
+ * NULL-terminated if len > 0.
+ *
+ * The JSON name always defaults to a camelCased version of the regular
+ * name. However if the regular name is unset, the JSON name will be unset
+ * also.
+ */
+ size_t GetJsonName(char* buf, size_t len) const;
+
+ /* Convenience version of the above function which copies the JSON name
+ * into the given string, returning false if the name is not set. */
+ template <class T>
+ bool GetJsonName(T* str) {
+ str->resize(GetJsonName(NULL, 0));
+ GetJsonName(&(*str)[0], str->size());
+ return str->size() > 0;
+ }
+
/* For UPB_TYPE_MESSAGE fields only where is_tag_delimited() == false,
* indicates whether this field should have lazy parsing handlers that yield
* the unparsed string for the submessage.
@@ -1557,7 +2006,7 @@ class upb::FieldDef {
* whatever message this field belongs to. Guaranteed to be less than
* f->containing_type()->field_count(). May only be accessed once the def has
* been finalized. */
- int index() const;
+ uint32_t index() const;
/* The MessageDef to which this field belongs.
*
@@ -1589,6 +2038,18 @@ class upb::FieldDef {
bool IsPrimitive() const;
bool IsMap() const;
+ /* Whether this field must be able to explicitly represent presence:
+ *
+ * * This is always false for repeated fields (an empty repeated field is
+ * equivalent to a repeated field with zero entries).
+ *
+ * * This is always true for submessages.
+ *
+ * * For other fields, it depends on the message (see
+ * MessageDef::SetPrimitivesHavePresence())
+ */
+ bool HasPresence() const;
+
/* How integers are encoded. Only meaningful for integer types.
* Defaults to UPB_INTFMT_VARIABLE, and is reset when "type" changes. */
IntegerFormat integer_format() const;
@@ -1690,6 +2151,16 @@ class upb::FieldDef {
bool set_name(const char* name, upb::Status* s);
bool set_name(const std::string& name, upb::Status* s);
+ /* Sets the JSON name to the given string. */
+ /* TODO(haberman): implement. Right now only default json_name (camelCase)
+ * is supported. */
+ bool set_json_name(const char* json_name, upb::Status* s);
+ bool set_json_name(const std::string& name, upb::Status* s);
+
+ /* Clears the JSON name. This will make it revert to its default, which is
+ * a camelCased version of the regular field name. */
+ void clear_json_name();
+
void set_integer_format(IntegerFormat format);
bool set_tag_delimited(bool tag_delimited, upb::Status* s);
@@ -1754,6 +2225,7 @@ const char *upb_fielddef_name(const upb_fielddef *f);
bool upb_fielddef_isextension(const upb_fielddef *f);
bool upb_fielddef_lazy(const upb_fielddef *f);
bool upb_fielddef_packed(const upb_fielddef *f);
+size_t upb_fielddef_getjsonname(const upb_fielddef *f, char *buf, size_t len);
const upb_msgdef *upb_fielddef_containingtype(const upb_fielddef *f);
const upb_oneofdef *upb_fielddef_containingoneof(const upb_fielddef *f);
upb_msgdef *upb_fielddef_containingtype_mutable(upb_fielddef *f);
@@ -1766,6 +2238,7 @@ bool upb_fielddef_isstring(const upb_fielddef *f);
bool upb_fielddef_isseq(const upb_fielddef *f);
bool upb_fielddef_isprimitive(const upb_fielddef *f);
bool upb_fielddef_ismap(const upb_fielddef *f);
+bool upb_fielddef_haspresence(const upb_fielddef *f);
int64_t upb_fielddef_defaultint64(const upb_fielddef *f);
int32_t upb_fielddef_defaultint32(const upb_fielddef *f);
uint64_t upb_fielddef_defaultuint64(const upb_fielddef *f);
@@ -1787,6 +2260,8 @@ void upb_fielddef_setdescriptortype(upb_fielddef *f, int type);
void upb_fielddef_setlabel(upb_fielddef *f, upb_label_t label);
bool upb_fielddef_setnumber(upb_fielddef *f, uint32_t number, upb_status *s);
bool upb_fielddef_setname(upb_fielddef *f, const char *name, upb_status *s);
+bool upb_fielddef_setjsonname(upb_fielddef *f, const char *name, upb_status *s);
+bool upb_fielddef_clearjsonname(upb_fielddef *f);
bool upb_fielddef_setcontainingtypename(upb_fielddef *f, const char *name,
upb_status *s);
void upb_fielddef_setisextension(upb_fielddef *f, bool is_extension);
@@ -1827,6 +2302,10 @@ UPB_END_EXTERN_C
typedef upb_inttable_iter upb_msg_field_iter;
typedef upb_strtable_iter upb_msg_oneof_iter;
+/* Well-known field tag numbers for map-entry messages. */
+#define UPB_MAPENTRY_KEY 1
+#define UPB_MAPENTRY_VALUE 2
+
#ifdef __cplusplus
/* Structure that describes a single .proto message type.
@@ -1842,6 +2321,7 @@ class upb::MessageDef {
/* Functionality from upb::Def. */
const char* full_name() const;
+ const char* name() const;
bool set_full_name(const char* fullname, Status* s);
bool set_full_name(const std::string& fullname, Status* s);
@@ -1884,6 +2364,16 @@ class upb::MessageDef {
bool AddOneof(OneofDef* o, Status* s);
bool AddOneof(const reffed_ptr<OneofDef>& o, Status* s);
+ upb_syntax_t syntax() const;
+
+ /* Returns false if we don't support this syntax value. */
+ bool set_syntax(upb_syntax_t syntax);
+
+ /* Set this to false to indicate that primitive fields should not have
+ * explicit presence information associated with them. This will affect all
+ * fields added to this message. Defaults to true. */
+ void SetPrimitivesHavePresence(bool have_presence);
+
/* These return NULL if the field is not found. */
FieldDef* FindFieldByNumber(uint32_t number);
FieldDef* FindFieldByName(const char *name, size_t len);
@@ -2069,14 +2559,20 @@ UPB_REFCOUNTED_CMETHODS(upb_msgdef, upb_msgdef_upcast2)
bool upb_msgdef_freeze(upb_msgdef *m, upb_status *status);
+upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner);
const char *upb_msgdef_fullname(const upb_msgdef *m);
-bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname, upb_status *s);
+const char *upb_msgdef_name(const upb_msgdef *m);
+int upb_msgdef_numoneofs(const upb_msgdef *m);
+upb_syntax_t upb_msgdef_syntax(const upb_msgdef *m);
-upb_msgdef *upb_msgdef_dup(const upb_msgdef *m, const void *owner);
bool upb_msgdef_addfield(upb_msgdef *m, upb_fielddef *f, const void *ref_donor,
upb_status *s);
bool upb_msgdef_addoneof(upb_msgdef *m, upb_oneofdef *o, const void *ref_donor,
upb_status *s);
+bool upb_msgdef_setfullname(upb_msgdef *m, const char *fullname, upb_status *s);
+void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry);
+bool upb_msgdef_mapentry(const upb_msgdef *m);
+bool upb_msgdef_setsyntax(upb_msgdef *m, upb_syntax_t syntax);
/* Field lookup in a couple of different variations:
* - itof = int to field
@@ -2118,18 +2614,21 @@ UPB_INLINE upb_oneofdef *upb_msgdef_ntoo_mutable(upb_msgdef *m,
return (upb_oneofdef *)upb_msgdef_ntoo(m, name, len);
}
-void upb_msgdef_setmapentry(upb_msgdef *m, bool map_entry);
-bool upb_msgdef_mapentry(const upb_msgdef *m);
+/* Lookup of either field or oneof by name. Returns whether either was found.
+ * If the return is true, then the found def will be set, and the non-found
+ * one set to NULL. */
+bool upb_msgdef_lookupname(const upb_msgdef *m, const char *name, size_t len,
+ const upb_fielddef **f, const upb_oneofdef **o);
-/* Well-known field tag numbers for map-entry messages. */
-#define UPB_MAPENTRY_KEY 1
-#define UPB_MAPENTRY_VALUE 2
-
-const upb_oneofdef *upb_msgdef_findoneof(const upb_msgdef *m,
- const char *name);
-int upb_msgdef_numoneofs(const upb_msgdef *m);
+UPB_INLINE bool upb_msgdef_lookupnamez(const upb_msgdef *m, const char *name,
+ const upb_fielddef **f,
+ const upb_oneofdef **o) {
+ return upb_msgdef_lookupname(m, name, strlen(name), f, o);
+}
-/* upb_msg_field_iter i;
+/* Iteration over fields and oneofs. For example:
+ *
+ * upb_msg_field_iter i;
* for(upb_msg_field_begin(&i, m);
* !upb_msg_field_done(&i);
* upb_msg_field_next(&i)) {
@@ -2175,6 +2674,7 @@ class upb::EnumDef {
/* Functionality from upb::Def. */
const char* full_name() const;
+ const char* name() const;
bool set_full_name(const char* fullname, Status* s);
bool set_full_name(const std::string& fullname, Status* s);
@@ -2249,6 +2749,7 @@ bool upb_enumdef_freeze(upb_enumdef *e, upb_status *status);
/* From upb_def. */
const char *upb_enumdef_fullname(const upb_enumdef *e);
+const char *upb_enumdef_name(const upb_enumdef *e);
bool upb_enumdef_setfullname(upb_enumdef *e, const char *fullname,
upb_status *s);
@@ -2290,8 +2791,7 @@ typedef upb_inttable_iter upb_oneof_iter;
#ifdef __cplusplus
-/* Class that represents a oneof. Its base class is upb::Def (convert with
- * upb::upcast()). */
+/* Class that represents a oneof. */
class upb::OneofDef {
public:
/* Returns NULL if memory allocation failed. */
@@ -2300,9 +2800,6 @@ class upb::OneofDef {
/* upb::RefCounted methods like Ref()/Unref(). */
UPB_REFCOUNTED_CPPMETHODS
- /* Functionality from upb::Def. */
- const char* full_name() const;
-
/* Returns the MessageDef that owns this OneofDef. */
const MessageDef* containing_type() const;
@@ -2310,6 +2807,7 @@ class upb::OneofDef {
* by name once added to a message def. */
const char* name() const;
bool set_name(const char* name, Status* s);
+ bool set_name(const std::string& name, Status* s);
/* Returns the number of fields currently defined in the oneof. */
int field_count() const;
@@ -2403,7 +2901,7 @@ upb_oneofdef *upb_oneofdef_new(const void *owner);
upb_oneofdef *upb_oneofdef_dup(const upb_oneofdef *o, const void *owner);
/* Include upb_refcounted methods like upb_oneofdef_ref(). */
-UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast2)
+UPB_REFCOUNTED_CMETHODS(upb_oneofdef, upb_oneofdef_upcast)
const char *upb_oneofdef_name(const upb_oneofdef *o);
bool upb_oneofdef_setname(upb_oneofdef *o, const char *name, upb_status *s);
@@ -2439,10 +2937,124 @@ void upb_oneof_iter_setdone(upb_oneof_iter *iter);
UPB_END_EXTERN_C
+
+/* upb::FileDef ***************************************************************/
+
+#ifdef __cplusplus
+
+/* Class that represents a .proto file with some things defined in it.
+ *
+ * Many users won't care about FileDefs, but they are necessary if you want to
+ * read the values of file-level options. */
+class upb::FileDef {
+ public:
+ /* Returns NULL if memory allocation failed. */
+ static reffed_ptr<FileDef> New();
+
+ /* upb::RefCounted methods like Ref()/Unref(). */
+ UPB_REFCOUNTED_CPPMETHODS
+
+ /* Get/set name of the file (eg. "foo/bar.proto"). */
+ const char* name() const;
+ bool set_name(const char* name, Status* s);
+ bool set_name(const std::string& name, Status* s);
+
+ /* Package name for definitions inside the file (eg. "foo.bar"). */
+ const char* package() const;
+ bool set_package(const char* package, Status* s);
+
+ /* Syntax for the file. Defaults to proto2. */
+ upb_syntax_t syntax() const;
+ void set_syntax(upb_syntax_t syntax);
+
+ /* Get the list of defs from the file. These are returned in the order that
+ * they were added to the FileDef. */
+ int def_count() const;
+ const Def* def(int index) const;
+ Def* def(int index);
+
+ /* Get the list of dependencies from the file. These are returned in the
+ * order that they were added to the FileDef. */
+ int dependency_count() const;
+ const FileDef* dependency(int index) const;
+
+ /* Adds defs to this file. The def must not already belong to another
+ * file.
+ *
+ * Note: this does *not* ensure that this def's name is unique in this file!
+ * Use a SymbolTable if you want to check this property. Especially since
+ * properly checking uniqueness would require a check across *all* files
+ * (including dependencies). */
+ bool AddDef(Def* def, Status* s);
+ bool AddMessage(MessageDef* m, Status* s);
+ bool AddEnum(EnumDef* e, Status* s);
+ bool AddExtension(FieldDef* f, Status* s);
+
+ /* Adds a dependency of this file. */
+ bool AddDependency(const FileDef* file);
+
+ /* Freezes this FileDef and all messages/enums under it. All subdefs must be
+ * resolved and all messages/enums must validate. Returns true if this
+ * succeeded.
+ *
+ * TODO(haberman): should we care whether the file's dependencies are frozen
+ * already? */
+ bool Freeze(Status* s);
+
+ private:
+ UPB_DISALLOW_POD_OPS(FileDef, upb::FileDef)
+};
+
+#endif
+
+UPB_BEGIN_EXTERN_C
+
+upb_filedef *upb_filedef_new(const void *owner);
+
+/* Include upb_refcounted methods like upb_msgdef_ref(). */
+UPB_REFCOUNTED_CMETHODS(upb_filedef, upb_filedef_upcast)
+
+const char *upb_filedef_name(const upb_filedef *f);
+const char *upb_filedef_package(const upb_filedef *f);
+upb_syntax_t upb_filedef_syntax(const upb_filedef *f);
+size_t upb_filedef_defcount(const upb_filedef *f);
+size_t upb_filedef_depcount(const upb_filedef *f);
+const upb_def *upb_filedef_def(const upb_filedef *f, size_t i);
+const upb_filedef *upb_filedef_dep(const upb_filedef *f, size_t i);
+
+bool upb_filedef_freeze(upb_filedef *f, upb_status *s);
+bool upb_filedef_setname(upb_filedef *f, const char *name, upb_status *s);
+bool upb_filedef_setpackage(upb_filedef *f, const char *package, upb_status *s);
+bool upb_filedef_setsyntax(upb_filedef *f, upb_syntax_t syntax, upb_status *s);
+
+bool upb_filedef_adddef(upb_filedef *f, upb_def *def, const void *ref_donor,
+ upb_status *s);
+bool upb_filedef_adddep(upb_filedef *f, const upb_filedef *dep);
+
+UPB_INLINE bool upb_filedef_addmsg(upb_filedef *f, upb_msgdef *m,
+ const void *ref_donor, upb_status *s) {
+ return upb_filedef_adddef(f, upb_msgdef_upcast_mutable(m), ref_donor, s);
+}
+
+UPB_INLINE bool upb_filedef_addenum(upb_filedef *f, upb_enumdef *e,
+ const void *ref_donor, upb_status *s) {
+ return upb_filedef_adddef(f, upb_enumdef_upcast_mutable(e), ref_donor, s);
+}
+
+UPB_INLINE bool upb_filedef_addext(upb_filedef *file, upb_fielddef *f,
+ const void *ref_donor, upb_status *s) {
+ return upb_filedef_adddef(file, upb_fielddef_upcast_mutable(f), ref_donor, s);
+}
+UPB_INLINE upb_def *upb_filedef_mutabledef(upb_filedef *f, int i) {
+ return (upb_def*)upb_filedef_def(f, i);
+}
+
+UPB_END_EXTERN_C
+
#ifdef __cplusplus
UPB_INLINE const char* upb_safecstr(const std::string& str) {
- assert(str.size() == std::strlen(str.c_str()));
+ UPB_ASSERT(str.size() == std::strlen(str.c_str()));
return str.c_str();
}
@@ -2454,13 +3066,14 @@ inline Def* Def::Dup(const void* owner) const {
}
inline Def::Type Def::def_type() const { return upb_def_type(this); }
inline const char* Def::full_name() const { return upb_def_fullname(this); }
+inline const char* Def::name() const { return upb_def_name(this); }
inline bool Def::set_full_name(const char* fullname, Status* s) {
return upb_def_setfullname(this, fullname, s);
}
inline bool Def::set_full_name(const std::string& fullname, Status* s) {
return upb_def_setfullname(this, upb_safecstr(fullname), s);
}
-inline bool Def::Freeze(Def* const* defs, int n, Status* status) {
+inline bool Def::Freeze(Def* const* defs, size_t n, Status* status) {
return upb_def_freeze(defs, n, status);
}
inline bool Def::Freeze(const std::vector<Def*>& defs, Status* status) {
@@ -2480,19 +3093,19 @@ inline bool FieldDef::CheckIntegerFormat(int32_t val) {
return upb_fielddef_checkintfmt(val);
}
inline FieldDef::Type FieldDef::ConvertType(int32_t val) {
- assert(CheckType(val));
+ UPB_ASSERT(CheckType(val));
return static_cast<FieldDef::Type>(val);
}
inline FieldDef::Label FieldDef::ConvertLabel(int32_t val) {
- assert(CheckLabel(val));
+ UPB_ASSERT(CheckLabel(val));
return static_cast<FieldDef::Label>(val);
}
inline FieldDef::DescriptorType FieldDef::ConvertDescriptorType(int32_t val) {
- assert(CheckDescriptorType(val));
+ UPB_ASSERT(CheckDescriptorType(val));
return static_cast<FieldDef::DescriptorType>(val);
}
inline FieldDef::IntegerFormat FieldDef::ConvertIntegerFormat(int32_t val) {
- assert(CheckIntegerFormat(val));
+ UPB_ASSERT(CheckIntegerFormat(val));
return static_cast<FieldDef::IntegerFormat>(val);
}
@@ -2527,6 +3140,9 @@ inline const char* FieldDef::name() const { return upb_fielddef_name(this); }
inline bool FieldDef::is_extension() const {
return upb_fielddef_isextension(this);
}
+inline size_t FieldDef::GetJsonName(char* buf, size_t len) const {
+ return upb_fielddef_getjsonname(this, buf, len);
+}
inline bool FieldDef::lazy() const {
return upb_fielddef_lazy(this);
}
@@ -2536,6 +3152,9 @@ inline void FieldDef::set_lazy(bool lazy) {
inline bool FieldDef::packed() const {
return upb_fielddef_packed(this);
}
+inline uint32_t FieldDef::index() const {
+ return upb_fielddef_index(this);
+}
inline void FieldDef::set_packed(bool packed) {
upb_fielddef_setpacked(this, packed);
}
@@ -2557,6 +3176,15 @@ inline bool FieldDef::set_name(const char *name, Status* s) {
inline bool FieldDef::set_name(const std::string& name, Status* s) {
return upb_fielddef_setname(this, upb_safecstr(name), s);
}
+inline bool FieldDef::set_json_name(const char *name, Status* s) {
+ return upb_fielddef_setjsonname(this, name, s);
+}
+inline bool FieldDef::set_json_name(const std::string& name, Status* s) {
+ return upb_fielddef_setjsonname(this, upb_safecstr(name), s);
+}
+inline void FieldDef::clear_json_name() {
+ upb_fielddef_clearjsonname(this);
+}
inline bool FieldDef::set_containing_type_name(const char *name, Status* s) {
return upb_fielddef_setcontainingtypename(this, name, s);
}
@@ -2671,12 +3299,21 @@ inline reffed_ptr<MessageDef> MessageDef::New() {
inline const char *MessageDef::full_name() const {
return upb_msgdef_fullname(this);
}
+inline const char *MessageDef::name() const {
+ return upb_msgdef_name(this);
+}
+inline upb_syntax_t MessageDef::syntax() const {
+ return upb_msgdef_syntax(this);
+}
inline bool MessageDef::set_full_name(const char* fullname, Status* s) {
return upb_msgdef_setfullname(this, fullname, s);
}
inline bool MessageDef::set_full_name(const std::string& fullname, Status* s) {
return upb_msgdef_setfullname(this, upb_safecstr(fullname), s);
}
+inline bool MessageDef::set_syntax(upb_syntax_t syntax) {
+ return upb_msgdef_setsyntax(this, syntax);
+}
inline bool MessageDef::Freeze(Status* status) {
return upb_msgdef_freeze(this, status);
}
@@ -2858,6 +3495,9 @@ inline reffed_ptr<EnumDef> EnumDef::New() {
inline const char* EnumDef::full_name() const {
return upb_enumdef_fullname(this);
}
+inline const char* EnumDef::name() const {
+ return upb_enumdef_name(this);
+}
inline bool EnumDef::set_full_name(const char* fullname, Status* s) {
return upb_enumdef_setfullname(this, fullname, s);
}
@@ -2907,9 +3547,6 @@ inline reffed_ptr<OneofDef> OneofDef::New() {
upb_oneofdef *o = upb_oneofdef_new(&o);
return reffed_ptr<OneofDef>(o, &o);
}
-inline const char* OneofDef::full_name() const {
- return upb_oneofdef_name(this);
-}
inline const MessageDef* OneofDef::containing_type() const {
return upb_oneofdef_containingtype(this);
@@ -2920,6 +3557,9 @@ inline const char* OneofDef::name() const {
inline bool OneofDef::set_name(const char* name, Status* s) {
return upb_oneofdef_setname(this, name, s);
}
+inline bool OneofDef::set_name(const std::string& name, Status* s) {
+ return upb_oneofdef_setname(this, upb_safecstr(name), s);
+}
inline int OneofDef::field_count() const {
return upb_oneofdef_numfields(this);
}
@@ -2988,6 +3628,57 @@ inline bool OneofDef::const_iterator::operator!=(
return !(*this == other);
}
+inline reffed_ptr<FileDef> FileDef::New() {
+ upb_filedef *f = upb_filedef_new(&f);
+ return reffed_ptr<FileDef>(f, &f);
+}
+
+inline const char* FileDef::name() const {
+ return upb_filedef_name(this);
+}
+inline bool FileDef::set_name(const char* name, Status* s) {
+ return upb_filedef_setname(this, name, s);
+}
+inline bool FileDef::set_name(const std::string& name, Status* s) {
+ return upb_filedef_setname(this, upb_safecstr(name), s);
+}
+inline const char* FileDef::package() const {
+ return upb_filedef_package(this);
+}
+inline bool FileDef::set_package(const char* package, Status* s) {
+ return upb_filedef_setpackage(this, package, s);
+}
+inline int FileDef::def_count() const {
+ return upb_filedef_defcount(this);
+}
+inline const Def* FileDef::def(int index) const {
+ return upb_filedef_def(this, index);
+}
+inline Def* FileDef::def(int index) {
+ return const_cast<Def*>(upb_filedef_def(this, index));
+}
+inline int FileDef::dependency_count() const {
+ return upb_filedef_depcount(this);
+}
+inline const FileDef* FileDef::dependency(int index) const {
+ return upb_filedef_dep(this, index);
+}
+inline bool FileDef::AddDef(Def* def, Status* s) {
+ return upb_filedef_adddef(this, def, NULL, s);
+}
+inline bool FileDef::AddMessage(MessageDef* m, Status* s) {
+ return upb_filedef_addmsg(this, m, NULL, s);
+}
+inline bool FileDef::AddEnum(EnumDef* e, Status* s) {
+ return upb_filedef_addenum(this, e, NULL, s);
+}
+inline bool FileDef::AddExtension(FieldDef* f, Status* s) {
+ return upb_filedef_addext(this, f, NULL, s);
+}
+inline bool FileDef::AddDependency(const FileDef* file) {
+ return upb_filedef_adddep(this, file);
+}
+
} /* namespace upb */
#endif
@@ -3026,6 +3717,7 @@ struct upb_def {
upb_refcounted base;
const char *fullname;
+ const upb_filedef* file;
char type; /* A upb_deftype_t (char to save space) */
/* Used as a flag during the def's mutable stage. Must be false unless
@@ -3035,8 +3727,8 @@ struct upb_def {
bool came_from_user;
};
-#define UPB_DEF_INIT(name, type, refs, ref2s) \
- { UPB_REFCOUNT_INIT(refs, ref2s), name, type, false }
+#define UPB_DEF_INIT(name, type, vtbl, refs, ref2s) \
+ { UPB_REFCOUNT_INIT(vtbl, refs, ref2s), name, NULL, type, false }
/* upb_fielddef ***************************************************************/
@@ -3076,12 +3768,14 @@ struct upb_fielddef {
uint32_t index_;
};
+extern const struct upb_refcounted_vtbl upb_fielddef_vtbl;
+
#define UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, \
packed, name, num, msgdef, subdef, selector_base, \
index, defaultval, refs, ref2s) \
{ \
- UPB_DEF_INIT(name, UPB_DEF_FIELD, refs, ref2s), defaultval, {msgdef}, \
- {subdef}, NULL, false, false, \
+ UPB_DEF_INIT(name, UPB_DEF_FIELD, &upb_fielddef_vtbl, refs, ref2s), \
+ defaultval, {msgdef}, {subdef}, NULL, false, false, \
type == UPB_TYPE_STRING || type == UPB_TYPE_BYTES, true, is_extension, \
lazy, packed, intfmt, tagdelim, type, label, num, selector_base, index \
}
@@ -3097,27 +3791,26 @@ struct upb_msgdef {
/* Tables for looking up fields by number and name. */
upb_inttable itof; /* int to field */
- upb_strtable ntof; /* name to field */
+ upb_strtable ntof; /* name to field/oneof */
- /* Tables for looking up oneofs by name. */
- upb_strtable ntoo; /* name to oneof */
-
- /* Is this a map-entry message?
- * TODO: set this flag properly for static descriptors; regenerate
- * descriptor.upb.c. */
+ /* Is this a map-entry message? */
bool map_entry;
+ /* Whether this message has proto2 or proto3 semantics. */
+ upb_syntax_t syntax;
+
/* TODO(haberman): proper extension ranges (there can be multiple). */
};
+extern const struct upb_refcounted_vtbl upb_msgdef_vtbl;
+
/* TODO: also support static initialization of the oneofs table. This will be
* needed if we compile in descriptors that contain oneofs. */
#define UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, \
- refs, ref2s) \
+ map_entry, syntax, refs, ref2s) \
{ \
- UPB_DEF_INIT(name, UPB_DEF_MSG, refs, ref2s), selector_count, \
- submsg_field_count, itof, ntof, \
- UPB_EMPTY_STRTABLE_INIT(UPB_CTYPE_PTR), false \
+ UPB_DEF_INIT(name, UPB_DEF_MSG, &upb_fielddef_vtbl, refs, ref2s), \
+ selector_count, submsg_field_count, itof, ntof, map_entry, syntax \
}
@@ -3131,22 +3824,28 @@ struct upb_enumdef {
int32_t defaultval;
};
+extern const struct upb_refcounted_vtbl upb_enumdef_vtbl;
+
#define UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval, refs, ref2s) \
- { UPB_DEF_INIT(name, UPB_DEF_ENUM, refs, ref2s), ntoi, iton, defaultval }
+ { UPB_DEF_INIT(name, UPB_DEF_ENUM, &upb_enumdef_vtbl, refs, ref2s), ntoi, \
+ iton, defaultval }
/* upb_oneofdef ***************************************************************/
struct upb_oneofdef {
- upb_def base;
+ upb_refcounted base;
+ const char *name;
upb_strtable ntof;
upb_inttable itof;
const upb_msgdef *parent;
};
+extern const struct upb_refcounted_vtbl upb_oneofdef_vtbl;
+
#define UPB_ONEOFDEF_INIT(name, ntof, itof, refs, ref2s) \
- { UPB_DEF_INIT(name, UPB_DEF_ENUM, refs, ref2s), ntof, itof }
+ { UPB_REFCOUNT_INIT(&upb_oneofdef_vtbl, refs, ref2s), name, ntof, itof }
/* upb_symtab *****************************************************************/
@@ -3157,9 +3856,18 @@ struct upb_symtab {
upb_strtable symtab;
};
-#define UPB_SYMTAB_INIT(symtab, refs, ref2s) \
- { UPB_REFCOUNT_INIT(refs, ref2s), symtab }
+struct upb_filedef {
+ upb_refcounted base;
+ const char *name;
+ const char *package;
+ upb_syntax_t syntax;
+
+ upb_inttable defs;
+ upb_inttable deps;
+};
+
+extern const struct upb_refcounted_vtbl upb_filedef_vtbl;
#endif /* UPB_STATICINIT_H_ */
/*
@@ -3773,7 +4481,7 @@ template <class T> class Handler {
void AddCleanup(Handlers* h) const {
if (cleanup_func_) {
bool ok = h->AddCleanup(cleanup_data_, cleanup_func_);
- UPB_ASSERT_VAR(ok, ok);
+ UPB_ASSERT(ok);
}
}
@@ -4793,7 +5501,7 @@ struct ConvertParams<BoundFunc5<R, P1, P2, P3, P4, P5, F, I>, T> {
inline bool Handlers::SetValueHandler<vtype>( \
const FieldDef *f, \
const Handlers::utype ## Handler& handler) { \
- assert(!handler.registered_); \
+ UPB_ASSERT(!handler.registered_); \
handler.AddCleanup(this); \
handler.registered_ = true; \
return upb_handlers_set##ltype(this, f, handler.handler_, &handler.attr_); \
@@ -4905,7 +5613,7 @@ inline Handler<T>::Handler(F func)
template <class T>
inline Handler<T>::~Handler() {
- assert(registered_);
+ UPB_ASSERT(registered_);
}
inline HandlerAttributes::HandlerAttributes() { upb_handlerattr_init(this); }
@@ -4991,63 +5699,63 @@ inline bool Handlers::AddCleanup(void *p, upb_handlerfree *func) {
}
inline bool Handlers::SetStartMessageHandler(
const Handlers::StartMessageHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartmsg(this, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndMessageHandler(
const Handlers::EndMessageHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendmsg(this, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartStringHandler(const FieldDef *f,
const StartStringHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartstr(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndStringHandler(const FieldDef *f,
const EndFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendstr(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStringHandler(const FieldDef *f,
const StringHandler& handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstring(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartSequenceHandler(
const FieldDef *f, const StartFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartseq(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetStartSubMessageHandler(
const FieldDef *f, const StartFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setstartsubmsg(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndSubMessageHandler(const FieldDef *f,
const EndFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendsubmsg(this, f, handler.handler_, &handler.attr_);
}
inline bool Handlers::SetEndSequenceHandler(const FieldDef *f,
const EndFieldHandler &handler) {
- assert(!handler.registered_);
+ UPB_ASSERT(!handler.registered_);
handler.registered_ = true;
handler.AddCleanup(this);
return upb_handlers_setendseq(this, f, handler.handler_, &handler.attr_);
@@ -5102,267 +5810,6 @@ inline BytesHandler::~BytesHandler() {}
#endif /* UPB_HANDLERS_H */
/*
-** upb::Environment (upb_env)
-**
-** A upb::Environment provides a means for injecting malloc and an
-** error-reporting callback into encoders/decoders. This allows them to be
-** independent of nearly all assumptions about their actual environment.
-**
-** It is also a container for allocating the encoders/decoders themselves that
-** insulates clients from knowing their actual size. This provides ABI
-** compatibility even if the size of the objects change. And this allows the
-** structure definitions to be in the .c files instead of the .h files, making
-** the .h files smaller and more readable.
-*/
-
-
-#ifndef UPB_ENV_H_
-#define UPB_ENV_H_
-
-#ifdef __cplusplus
-namespace upb {
-class Environment;
-class SeededAllocator;
-}
-#endif
-
-UPB_DECLARE_TYPE(upb::Environment, upb_env)
-UPB_DECLARE_TYPE(upb::SeededAllocator, upb_seededalloc)
-
-typedef void *upb_alloc_func(void *ud, void *ptr, size_t oldsize, size_t size);
-typedef void upb_cleanup_func(void *ud);
-typedef bool upb_error_func(void *ud, const upb_status *status);
-
-#ifdef __cplusplus
-
-/* An environment is *not* thread-safe. */
-class upb::Environment {
- public:
- Environment();
- ~Environment();
-
- /* Set a custom memory allocation function for the environment. May ONLY
- * be called before any calls to Malloc()/Realloc()/AddCleanup() below.
- * If this is not called, the system realloc() function will be used.
- * The given user pointer "ud" will be passed to the allocation function.
- *
- * The allocation function will not receive corresponding "free" calls. it
- * must ensure that the memory is valid for the lifetime of the Environment,
- * but it may be reclaimed any time thereafter. The likely usage is that
- * "ud" points to a stateful allocator, and that the allocator frees all
- * memory, arena-style, when it is destroyed. In this case the allocator must
- * outlive the Environment. Another possibility is that the allocation
- * function returns GC-able memory that is guaranteed to be GC-rooted for the
- * life of the Environment. */
- void SetAllocationFunction(upb_alloc_func* alloc, void* ud);
-
- template<class T>
- void SetAllocator(T* allocator) {
- SetAllocationFunction(allocator->GetAllocationFunction(), allocator);
- }
-
- /* Set a custom error reporting function. */
- void SetErrorFunction(upb_error_func* func, void* ud);
-
- /* Set the error reporting function to simply copy the status to the given
- * status and abort. */
- void ReportErrorsTo(Status* status);
-
- /* Returns true if all allocations and AddCleanup() calls have succeeded,
- * and no errors were reported with ReportError() (except ones that recovered
- * successfully). */
- bool ok() const;
-
- /* Functions for use by encoders/decoders. **********************************/
-
- /* Reports an error to this environment's callback, returning true if
- * the caller should try to recover. */
- bool ReportError(const Status* status);
-
- /* Allocate memory. Uses the environment's allocation function.
- *
- * There is no need to free(). All memory will be freed automatically, but is
- * guaranteed to outlive the Environment. */
- void* Malloc(size_t size);
-
- /* Reallocate memory. Preserves "oldsize" bytes from the existing buffer
- * Requires: oldsize <= existing_size.
- *
- * TODO(haberman): should we also enforce that oldsize <= size? */
- void* Realloc(void* ptr, size_t oldsize, size_t size);
-
- /* Add a cleanup function to run when the environment is destroyed.
- * Returns false on out-of-memory.
- *
- * The first call to AddCleanup() after SetAllocationFunction() is guaranteed
- * to return true -- this makes it possible to robustly set a cleanup handler
- * for a custom allocation function. */
- bool AddCleanup(upb_cleanup_func* func, void* ud);
-
- /* Total number of bytes that have been allocated. It is undefined what
- * Realloc() does to this counter. */
- size_t BytesAllocated() const;
-
- private:
- UPB_DISALLOW_COPY_AND_ASSIGN(Environment)
-
-#else
-struct upb_env {
-#endif /* __cplusplus */
-
- bool ok_;
- size_t bytes_allocated;
-
- /* Alloc function. */
- upb_alloc_func *alloc;
- void *alloc_ud;
-
- /* Error-reporting function. */
- upb_error_func *err;
- void *err_ud;
-
- /* Userdata for default alloc func. */
- void *default_alloc_ud;
-
- /* Cleanup entries. Pointer to a cleanup_ent, defined in env.c */
- void *cleanup_head;
-
- /* For future expansion, since the size of this struct is exposed to users. */
- void *future1;
- void *future2;
-};
-
-UPB_BEGIN_EXTERN_C
-
-void upb_env_init(upb_env *e);
-void upb_env_uninit(upb_env *e);
-void upb_env_setallocfunc(upb_env *e, upb_alloc_func *func, void *ud);
-void upb_env_seterrorfunc(upb_env *e, upb_error_func *func, void *ud);
-void upb_env_reporterrorsto(upb_env *e, upb_status *status);
-bool upb_env_ok(const upb_env *e);
-bool upb_env_reporterror(upb_env *e, const upb_status *status);
-void *upb_env_malloc(upb_env *e, size_t size);
-void *upb_env_realloc(upb_env *e, void *ptr, size_t oldsize, size_t size);
-bool upb_env_addcleanup(upb_env *e, upb_cleanup_func *func, void *ud);
-size_t upb_env_bytesallocated(const upb_env *e);
-
-UPB_END_EXTERN_C
-
-#ifdef __cplusplus
-
-/* An allocator that allocates from an initial memory region (likely the stack)
- * before falling back to another allocator. */
-class upb::SeededAllocator {
- public:
- SeededAllocator(void *mem, size_t len);
- ~SeededAllocator();
-
- /* Set a custom fallback memory allocation function for the allocator, to use
- * once the initial region runs out.
- *
- * May ONLY be called before GetAllocationFunction(). If this is not
- * called, the system realloc() will be the fallback allocator. */
- void SetFallbackAllocator(upb_alloc_func *alloc, void *ud);
-
- /* Gets the allocation function for this allocator. */
- upb_alloc_func* GetAllocationFunction();
-
- private:
- UPB_DISALLOW_COPY_AND_ASSIGN(SeededAllocator)
-
-#else
-struct upb_seededalloc {
-#endif /* __cplusplus */
-
- /* Fallback alloc function. */
- upb_alloc_func *alloc;
- upb_cleanup_func *alloc_cleanup;
- void *alloc_ud;
- bool need_cleanup;
- bool returned_allocfunc;
-
- /* Userdata for default alloc func. */
- void *default_alloc_ud;
-
- /* Pointers for the initial memory region. */
- char *mem_base;
- char *mem_ptr;
- char *mem_limit;
-
- /* For future expansion, since the size of this struct is exposed to users. */
- void *future1;
- void *future2;
-};
-
-UPB_BEGIN_EXTERN_C
-
-void upb_seededalloc_init(upb_seededalloc *a, void *mem, size_t len);
-void upb_seededalloc_uninit(upb_seededalloc *a);
-void upb_seededalloc_setfallbackalloc(upb_seededalloc *a, upb_alloc_func *func,
- void *ud);
-upb_alloc_func *upb_seededalloc_getallocfunc(upb_seededalloc *a);
-
-UPB_END_EXTERN_C
-
-#ifdef __cplusplus
-
-namespace upb {
-
-inline Environment::Environment() {
- upb_env_init(this);
-}
-inline Environment::~Environment() {
- upb_env_uninit(this);
-}
-inline void Environment::SetAllocationFunction(upb_alloc_func *alloc,
- void *ud) {
- upb_env_setallocfunc(this, alloc, ud);
-}
-inline void Environment::SetErrorFunction(upb_error_func *func, void *ud) {
- upb_env_seterrorfunc(this, func, ud);
-}
-inline void Environment::ReportErrorsTo(Status* status) {
- upb_env_reporterrorsto(this, status);
-}
-inline bool Environment::ok() const {
- return upb_env_ok(this);
-}
-inline bool Environment::ReportError(const Status* status) {
- return upb_env_reporterror(this, status);
-}
-inline void *Environment::Malloc(size_t size) {
- return upb_env_malloc(this, size);
-}
-inline void *Environment::Realloc(void *ptr, size_t oldsize, size_t size) {
- return upb_env_realloc(this, ptr, oldsize, size);
-}
-inline bool Environment::AddCleanup(upb_cleanup_func *func, void *ud) {
- return upb_env_addcleanup(this, func, ud);
-}
-inline size_t Environment::BytesAllocated() const {
- return upb_env_bytesallocated(this);
-}
-
-inline SeededAllocator::SeededAllocator(void *mem, size_t len) {
- upb_seededalloc_init(this, mem, len);
-}
-inline SeededAllocator::~SeededAllocator() {
- upb_seededalloc_uninit(this);
-}
-inline void SeededAllocator::SetFallbackAllocator(upb_alloc_func *alloc,
- void *ud) {
- upb_seededalloc_setfallbackalloc(this, alloc, ud);
-}
-inline upb_alloc_func *SeededAllocator::GetAllocationFunction() {
- return upb_seededalloc_getallocfunc(this);
-}
-
-} /* namespace upb */
-
-#endif /* __cplusplus */
-
-#endif /* UPB_ENV_H_ */
-/*
** upb::Sink (upb_sink)
** upb::BytesSink (upb_bytessink)
**
@@ -6066,12 +6513,17 @@ class upb::SymbolTable {
* only a few messages are changing. We may want to add a way of adding a
* tree of frozen defs to the symtab (perhaps an alternate constructor where
* you pass the root of the tree?) */
- bool Add(Def*const* defs, int n, void* ref_donor, upb_status* status);
+ bool Add(Def*const* defs, size_t n, void* ref_donor, Status* status);
bool Add(const std::vector<Def*>& defs, void *owner, Status* status) {
return Add((Def*const*)&defs[0], defs.size(), owner, status);
}
+ /* Resolves all subdefs for messages in this file and attempts to freeze the
+ * file. If this succeeds, adds all the symbols to this SymbolTable
+ * (replacing any existing ones with the same names). */
+ bool AddFile(FileDef* file, Status* s);
+
private:
UPB_DISALLOW_POD_OPS(SymbolTable, upb::SymbolTable)
};
@@ -6092,8 +6544,9 @@ const upb_def *upb_symtab_resolve(const upb_symtab *s, const char *base,
const upb_def *upb_symtab_lookup(const upb_symtab *s, const char *sym);
const upb_msgdef *upb_symtab_lookupmsg(const upb_symtab *s, const char *sym);
const upb_enumdef *upb_symtab_lookupenum(const upb_symtab *s, const char *sym);
-bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, int n, void *ref_donor,
- upb_status *status);
+bool upb_symtab_add(upb_symtab *s, upb_def *const*defs, size_t n,
+ void *ref_donor, upb_status *status);
+bool upb_symtab_addfile(upb_symtab *s, upb_filedef *file, upb_status* status);
/* upb_symtab_iter i;
* for(upb_symtab_begin(&i, s, type); !upb_symtab_done(&i);
@@ -6135,9 +6588,12 @@ inline const MessageDef *SymbolTable::LookupMessage(const char *sym) const {
return upb_symtab_lookupmsg(this, sym);
}
inline bool SymbolTable::Add(
- Def*const* defs, int n, void* ref_donor, upb_status* status) {
+ Def*const* defs, size_t n, void* ref_donor, Status* status) {
return upb_symtab_add(this, (upb_def*const*)defs, n, ref_donor, status);
}
+inline bool SymbolTable::AddFile(FileDef* file, Status* s) {
+ return upb_symtab_addfile(this, file, s);
+}
} /* namespace upb */
#endif
@@ -6181,14 +6637,9 @@ class upb::descriptor::Reader {
/* The reader's input; this is where descriptor.proto data should be sent. */
Sink* input();
- /* Returns an array of all defs that have been parsed, and transfers ownership
- * of them to "owner". The number of defs is stored in *n. Ownership of the
- * returned array is retained and is invalidated by any other call into
- * Reader.
- *
- * These defs are not frozen or resolved; they are ready to be added to a
- * symtab. */
- upb::Def** GetDefs(void* owner, int* n);
+ /* Use to get the FileDefs that have been parsed. */
+ size_t file_count() const;
+ FileDef* file(size_t i) const;
/* Builds and returns handlers for the reader, owned by "owner." */
static Handlers* NewHandlers(const void* owner);
@@ -6204,7 +6655,8 @@ UPB_BEGIN_EXTERN_C
/* C API. */
upb_descreader *upb_descreader_create(upb_env *e, const upb_handlers *h);
upb_sink *upb_descreader_input(upb_descreader *r);
-upb_def **upb_descreader_getdefs(upb_descreader *r, void *owner, int *n);
+size_t upb_descreader_filecount(const upb_descreader *r);
+upb_filedef *upb_descreader_file(const upb_descreader *r, size_t i);
const upb_handlers *upb_descreader_newhandlers(const void *owner);
UPB_END_EXTERN_C
@@ -6217,8 +6669,11 @@ inline Reader* Reader::Create(Environment* e, const Handlers *h) {
return upb_descreader_create(e, h);
}
inline Sink* Reader::input() { return upb_descreader_input(this); }
-inline upb::Def** Reader::GetDefs(void* owner, int* n) {
- return upb_descreader_getdefs(this, owner, n);
+inline size_t Reader::file_count() const {
+ return upb_descreader_filecount(this);
+}
+inline FileDef* Reader::file(size_t i) const {
+ return upb_descreader_file(this, i);
}
} /* namespace descriptor */
} /* namespace upb */
@@ -6231,519 +6686,290 @@ inline upb::Def** Reader::GetDefs(void* owner, int* n) {
* actually storing protobufs. It only contains *defs* which
* let you reflect over a protobuf *schema*.
*/
-/* This file was generated by upbc (the upb compiler).
+/* This file was generated by upbc (the upb compiler) from the input
+ * file:
+ *
+ * upb/descriptor/descriptor.proto
+ *
* Do not edit -- your changes will be discarded when the file is
* regenerated. */
-#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_UPB_H_
-#define GOOGLE_PROTOBUF_DESCRIPTOR_UPB_H_
+#ifndef UPB_DESCRIPTOR_DESCRIPTOR_PROTO_UPB_H_
+#define UPB_DESCRIPTOR_DESCRIPTOR_PROTO_UPB_H_
-#ifdef __cplusplus
UPB_BEGIN_EXTERN_C
-#endif
/* 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_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_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_STRING = 0,
+ google_protobuf_FieldOptions_CORD = 1,
+ google_protobuf_FieldOptions_STRING_PIECE = 2
} google_protobuf_FieldOptions_CType;
typedef enum {
- GOOGLE_PROTOBUF_FILEOPTIONS_SPEED = 1,
- GOOGLE_PROTOBUF_FILEOPTIONS_CODE_SIZE = 2,
- GOOGLE_PROTOBUF_FILEOPTIONS_LITE_RUNTIME = 3
+ 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;
-/* Selectors */
-
-/* google.protobuf.DescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_STARTSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_STARTSUBMSG 4
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_STARTSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_STARTSUBMSG 6
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_OPTIONS_STARTSUBMSG 7
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_STARTSEQ 8
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_ENDSEQ 9
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_FIELD_ENDSUBMSG 10
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_STARTSEQ 11
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_ENDSEQ 12
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NESTED_TYPE_ENDSUBMSG 13
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_STARTSEQ 14
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_ENDSEQ 15
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_ENUM_TYPE_ENDSUBMSG 16
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_STARTSEQ 17
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_ENDSEQ 18
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_RANGE_ENDSUBMSG 19
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_STARTSEQ 20
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_ENDSEQ 21
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSION_ENDSUBMSG 22
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_OPTIONS_ENDSUBMSG 23
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NAME_STRING 24
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NAME_STARTSTR 25
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_NAME_ENDSTR 26
-
-/* google.protobuf.DescriptorProto.ExtensionRange */
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSIONRANGE_START_INT32 2
-#define SEL_GOOGLE_PROTOBUF_DESCRIPTORPROTO_EXTENSIONRANGE_END_INT32 3
-
-/* google.protobuf.EnumDescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_STARTSEQ 4
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_ENDSEQ 5
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_VALUE_ENDSUBMSG 6
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 7
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_NAME_STRING 8
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_NAME_STARTSTR 9
-#define SEL_GOOGLE_PROTOBUF_ENUMDESCRIPTORPROTO_NAME_ENDSTR 10
-
-/* google.protobuf.EnumOptions */
-#define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_ENUMOPTIONS_ALLOW_ALIAS_BOOL 6
-
-/* google.protobuf.EnumValueDescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NAME_STRING 4
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NAME_STARTSTR 5
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NAME_ENDSTR 6
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEDESCRIPTORPROTO_NUMBER_INT32 7
-
-/* google.protobuf.EnumValueOptions */
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_ENUMVALUEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-
-/* google.protobuf.FieldDescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NAME_STRING 4
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NAME_STARTSTR 5
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NAME_ENDSTR 6
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_EXTENDEE_STRING 7
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_EXTENDEE_STARTSTR 8
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_EXTENDEE_ENDSTR 9
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_NUMBER_INT32 10
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_LABEL_INT32 11
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_INT32 12
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_NAME_STRING 13
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_NAME_STARTSTR 14
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_TYPE_NAME_ENDSTR 15
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_DEFAULT_VALUE_STRING 16
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_DEFAULT_VALUE_STARTSTR 17
-#define SEL_GOOGLE_PROTOBUF_FIELDDESCRIPTORPROTO_DEFAULT_VALUE_ENDSTR 18
-
-/* google.protobuf.FieldOptions */
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_CTYPE_INT32 6
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_PACKED_BOOL 7
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_DEPRECATED_BOOL 8
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_LAZY_BOOL 9
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_EXPERIMENTAL_MAP_KEY_STRING 10
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_EXPERIMENTAL_MAP_KEY_STARTSTR 11
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_EXPERIMENTAL_MAP_KEY_ENDSTR 12
-#define SEL_GOOGLE_PROTOBUF_FIELDOPTIONS_WEAK_BOOL 13
-
-/* google.protobuf.FileDescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_STARTSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_STARTSUBMSG 4
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_STARTSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 6
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SOURCE_CODE_INFO_STARTSUBMSG 7
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_STARTSEQ 8
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_ENDSEQ 9
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_MESSAGE_TYPE_ENDSUBMSG 10
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_STARTSEQ 11
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_ENDSEQ 12
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_ENUM_TYPE_ENDSUBMSG 13
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_STARTSEQ 14
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_ENDSEQ 15
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SERVICE_ENDSUBMSG 16
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_STARTSEQ 17
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_ENDSEQ 18
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_EXTENSION_ENDSUBMSG 19
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 20
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_SOURCE_CODE_INFO_ENDSUBMSG 21
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_NAME_STRING 22
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_NAME_STARTSTR 23
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_NAME_ENDSTR 24
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PACKAGE_STRING 25
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PACKAGE_STARTSTR 26
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PACKAGE_ENDSTR 27
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_STARTSEQ 28
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_ENDSEQ 29
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_STRING 30
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_STARTSTR 31
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_DEPENDENCY_ENDSTR 32
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PUBLIC_DEPENDENCY_STARTSEQ 33
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PUBLIC_DEPENDENCY_ENDSEQ 34
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_PUBLIC_DEPENDENCY_INT32 35
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_WEAK_DEPENDENCY_STARTSEQ 36
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_WEAK_DEPENDENCY_ENDSEQ 37
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORPROTO_WEAK_DEPENDENCY_INT32 38
-
-/* google.protobuf.FileDescriptorSet */
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_FILEDESCRIPTORSET_FILE_ENDSUBMSG 5
-
-/* google.protobuf.FileOptions */
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_PACKAGE_STRING 6
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_PACKAGE_STARTSTR 7
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_PACKAGE_ENDSTR 8
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_OUTER_CLASSNAME_STRING 9
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_OUTER_CLASSNAME_STARTSTR 10
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_OUTER_CLASSNAME_ENDSTR 11
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_OPTIMIZE_FOR_INT32 12
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_MULTIPLE_FILES_BOOL 13
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_GO_PACKAGE_STRING 14
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_GO_PACKAGE_STARTSTR 15
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_GO_PACKAGE_ENDSTR 16
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_CC_GENERIC_SERVICES_BOOL 17
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_GENERIC_SERVICES_BOOL 18
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_PY_GENERIC_SERVICES_BOOL 19
-#define SEL_GOOGLE_PROTOBUF_FILEOPTIONS_JAVA_GENERATE_EQUALS_AND_HASH_BOOL 20
-
-/* google.protobuf.MessageOptions */
-#define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_MESSAGE_SET_WIRE_FORMAT_BOOL 6
-#define SEL_GOOGLE_PROTOBUF_MESSAGEOPTIONS_NO_STANDARD_DESCRIPTOR_ACCESSOR_BOOL 7
-
-/* google.protobuf.MethodDescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_NAME_STRING 4
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_NAME_STARTSTR 5
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_NAME_ENDSTR 6
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_INPUT_TYPE_STRING 7
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_INPUT_TYPE_STARTSTR 8
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_INPUT_TYPE_ENDSTR 9
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OUTPUT_TYPE_STRING 10
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OUTPUT_TYPE_STARTSTR 11
-#define SEL_GOOGLE_PROTOBUF_METHODDESCRIPTORPROTO_OUTPUT_TYPE_ENDSTR 12
-
-/* google.protobuf.MethodOptions */
-#define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_METHODOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-
-/* google.protobuf.ServiceDescriptorProto */
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_OPTIONS_STARTSUBMSG 3
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_STARTSEQ 4
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_ENDSEQ 5
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_METHOD_ENDSUBMSG 6
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_OPTIONS_ENDSUBMSG 7
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_NAME_STRING 8
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_NAME_STARTSTR 9
-#define SEL_GOOGLE_PROTOBUF_SERVICEDESCRIPTORPROTO_NAME_ENDSTR 10
-
-/* google.protobuf.ServiceOptions */
-#define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_SERVICEOPTIONS_UNINTERPRETED_OPTION_ENDSUBMSG 5
-
-/* google.protobuf.SourceCodeInfo */
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_ENDSUBMSG 5
-
-/* google.protobuf.SourceCodeInfo.Location */
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_PATH_STARTSEQ 2
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_PATH_ENDSEQ 3
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_PATH_INT32 4
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_SPAN_STARTSEQ 5
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_SPAN_ENDSEQ 6
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_SPAN_INT32 7
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_LEADING_COMMENTS_STRING 8
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_LEADING_COMMENTS_STARTSTR 9
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_LEADING_COMMENTS_ENDSTR 10
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_TRAILING_COMMENTS_STRING 11
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_TRAILING_COMMENTS_STARTSTR 12
-#define SEL_GOOGLE_PROTOBUF_SOURCECODEINFO_LOCATION_TRAILING_COMMENTS_ENDSTR 13
-
-/* google.protobuf.UninterpretedOption */
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_STARTSUBMSG 2
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_STARTSEQ 3
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_ENDSEQ 4
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAME_ENDSUBMSG 5
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_IDENTIFIER_VALUE_STRING 6
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_IDENTIFIER_VALUE_STARTSTR 7
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_IDENTIFIER_VALUE_ENDSTR 8
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_POSITIVE_INT_VALUE_UINT64 9
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NEGATIVE_INT_VALUE_INT64 10
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_DOUBLE_VALUE_DOUBLE 11
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_STRING_VALUE_STRING 12
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_STRING_VALUE_STARTSTR 13
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_STRING_VALUE_ENDSTR 14
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_AGGREGATE_VALUE_STRING 15
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_AGGREGATE_VALUE_STARTSTR 16
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_AGGREGATE_VALUE_ENDSTR 17
-
-/* google.protobuf.UninterpretedOption.NamePart */
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_NAME_PART_STRING 2
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_NAME_PART_STARTSTR 3
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_NAME_PART_ENDSTR 4
-#define SEL_GOOGLE_PROTOBUF_UNINTERPRETEDOPTION_NAMEPART_IS_EXTENSION_BOOL 5
-
-const upb_symtab *upbdefs_google_protobuf_descriptor(const void *owner);
-
-/* MessageDefs */
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_DescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.DescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.DescriptorProto.ExtensionRange");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumDescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumValueDescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.EnumValueOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FieldDescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FieldOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FieldOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FileDescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FileDescriptorSet");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_FileOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.FileOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_MessageOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.MessageOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.MethodDescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_MethodOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.MethodOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.ServiceDescriptorProto");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_ServiceOptions(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.ServiceOptions");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.SourceCodeInfo");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.SourceCodeInfo.Location");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.UninterpretedOption");
- assert(m);
- return m;
-}
-UPB_INLINE const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart(const upb_symtab *s) {
- const upb_msgdef *m = upb_symtab_lookupmsg(s, "google.protobuf.UninterpretedOption.NamePart");
- assert(m);
- return m;
-}
-
-
-/* EnumDefs */
-UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label(const upb_symtab *s) {
- const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FieldDescriptorProto.Label");
- assert(e);
- return e;
-}
-UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type(const upb_symtab *s) {
- const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FieldDescriptorProto.Type");
- assert(e);
- return e;
-}
-UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType(const upb_symtab *s) {
- const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FieldOptions.CType");
- assert(e);
- return e;
-}
-UPB_INLINE const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode(const upb_symtab *s) {
- const upb_enumdef *e = upb_symtab_lookupenum(s, "google.protobuf.FileOptions.OptimizeMode");
- assert(e);
- return e;
-}
-
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_end(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto_ExtensionRange(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_start(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto_ExtensionRange(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_enum_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_extension(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_extension_range(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_field(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_nested_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_DescriptorProto(s), 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumDescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumDescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumDescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_allow_alias(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumOptions(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueDescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_number(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueDescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueDescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_EnumValueOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_default_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_extendee(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_label(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_number(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_type_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldDescriptorProto(s), 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_ctype(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_deprecated(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_experimental_map_key(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_lazy(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_packed(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_weak(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FieldOptions(s), 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_dependency(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_enum_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_extension(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 7); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_message_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_package(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_public_dependency(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_service(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_source_code_info(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_weak_dependency(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorProto(s), 11); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorSet_file(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileDescriptorSet(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_cc_generic_services(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 16); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_go_package(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 11); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_generate_equals_and_hash(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 20); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_generic_services(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 17); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_multiple_files(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 10); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_outer_classname(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_java_package(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_optimize_for(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 9); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_py_generic_services(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 18); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_FileOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_message_set_wire_format(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MessageOptions(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_no_standard_descriptor_accessor(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MessageOptions(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MessageOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_input_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_output_type(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodDescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_MethodOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_method(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceDescriptorProto(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceDescriptorProto(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_options(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceDescriptorProto(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_uninterpreted_option(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_ServiceOptions(s), 999); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_leading_comments(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_path(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_span(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_trailing_comments(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo_Location(s), 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_location(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_SourceCodeInfo(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_is_extension(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption_NamePart(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_name_part(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption_NamePart(s), 1); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_aggregate_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 8); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_double_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 6); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_identifier_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 3); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_name(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 2); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_negative_int_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 5); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_positive_int_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 4); }
-UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_string_value(const upb_symtab *s) { return upb_msgdef_itof(upbdefs_google_protobuf_UninterpretedOption(s), 7); }
+/* 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);
+const upb_msgdef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_EnumDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_EnumOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_EnumValueDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_EnumValueOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_FieldDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_FieldOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_FileDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_FileDescriptorSet_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_FileOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_MessageOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_MethodDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_MethodOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_OneofDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_ServiceDescriptorProto_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_ServiceOptions_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_SourceCodeInfo_Location_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_get(const void *owner);
+const upb_msgdef *upbdefs_google_protobuf_UninterpretedOption_NamePart_get(const void *owner);
+
+/* EnumDefs: call these functions to get a ref to an enumdef. */
+const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Label_get(const void *owner);
+const upb_enumdef *upbdefs_google_protobuf_FieldDescriptorProto_Type_get(const void *owner);
+const upb_enumdef *upbdefs_google_protobuf_FieldOptions_CType_get(const void *owner);
+const upb_enumdef *upbdefs_google_protobuf_FieldOptions_JSType_get(const void *owner);
+const upb_enumdef *upbdefs_google_protobuf_FileOptions_OptimizeMode_get(const void *owner);
+
+/* Functions to test whether this message is of a certain type. */
+UPB_INLINE bool upbdefs_google_protobuf_DescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.DescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.DescriptorProto.ExtensionRange") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.DescriptorProto.ReservedRange") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_EnumDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_EnumOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_EnumValueDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumValueDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_EnumValueOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.EnumValueOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FieldDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.FieldDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FieldOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.FieldOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FileDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.FileDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FileDescriptorSet_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.FileDescriptorSet") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FileOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.FileOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_MessageOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.MessageOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_MethodDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.MethodDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_MethodOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.MethodOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_OneofDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.OneofDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_ServiceDescriptorProto_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.ServiceDescriptorProto") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_ServiceOptions_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.ServiceOptions") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_SourceCodeInfo_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.SourceCodeInfo") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_SourceCodeInfo_Location_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.SourceCodeInfo.Location") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_UninterpretedOption_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.UninterpretedOption") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_UninterpretedOption_NamePart_is(const upb_msgdef *m) {
+ return strcmp(upb_msgdef_fullname(m), "google.protobuf.UninterpretedOption.NamePart") == 0;
+}
+
+/* Functions to test whether this enum is of a certain type. */
+UPB_INLINE bool upbdefs_google_protobuf_FieldDescriptorProto_Label_is(const upb_enumdef *e) {
+ return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldDescriptorProto.Label") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FieldDescriptorProto_Type_is(const upb_enumdef *e) {
+ return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldDescriptorProto.Type") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FieldOptions_CType_is(const upb_enumdef *e) {
+ return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldOptions.CType") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FieldOptions_JSType_is(const upb_enumdef *e) {
+ return strcmp(upb_enumdef_fullname(e), "google.protobuf.FieldOptions.JSType") == 0;
+}
+UPB_INLINE bool upbdefs_google_protobuf_FileOptions_OptimizeMode_is(const upb_enumdef *e) {
+ return strcmp(upb_enumdef_fullname(e), "google.protobuf.FileOptions.OptimizeMode") == 0;
+}
+
+
+/* Functions to get a fielddef from a msgdef reference. */
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_end(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ExtensionRange_f_start(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_end(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_ReservedRange_f_start(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_enum_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_extension_range(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_field(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_nested_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_oneof_decl(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_DescriptorProto_f_reserved_range(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumDescriptorProto_f_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_allow_alias(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_number(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_EnumValueOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_EnumValueOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_default_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_extendee(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_json_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_label(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_number(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_oneof_index(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldDescriptorProto_f_type_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_ctype(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_jstype(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_lazy(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_packed(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FieldOptions_f_weak(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_dependency(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_enum_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_extension(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_message_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_public_dependency(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_service(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_source_code_info(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_syntax(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 12); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorProto_f_weak_dependency(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m)); return upb_msgdef_itof(m, 11); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileDescriptorSet_f_file(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorSet_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_enable_arenas(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 31); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_cc_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 16); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_csharp_namespace(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 37); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 23); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_go_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 11); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generate_equals_and_hash(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 20); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 17); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_multiple_files(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 10); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_outer_classname(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_java_string_check_utf8(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 27); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_javanano_use_deprecated_package(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 38); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_objc_class_prefix(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 36); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_optimize_for(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 9); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_py_generic_services(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 18); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_FileOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_map_entry(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 7); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_message_set_wire_format(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_no_standard_descriptor_accessor(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MessageOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_client_streaming(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_input_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_output_type(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodDescriptorProto_f_server_streaming(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 33); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_MethodOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_MethodOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_OneofDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_OneofDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_method(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceDescriptorProto_f_options(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_deprecated(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 33); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_ServiceOptions_f_uninterpreted_option(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_ServiceOptions_is(m)); return upb_msgdef_itof(m, 999); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_comments(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_leading_detached_comments(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_path(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_span(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_Location_f_trailing_comments(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_SourceCodeInfo_f_location(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_is_extension(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_NamePart_f_name_part(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m)); return upb_msgdef_itof(m, 1); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_aggregate_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 8); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_double_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 6); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_identifier_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 3); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_name(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 2); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_negative_int_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 5); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_positive_int_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 4); }
+UPB_INLINE const upb_fielddef *upbdefs_google_protobuf_UninterpretedOption_f_string_value(const upb_msgdef *m) { UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m)); return upb_msgdef_itof(m, 7); }
UPB_END_EXTERN_C
@@ -6752,277 +6978,360 @@ UPB_END_EXTERN_C
namespace upbdefs {
namespace google {
namespace protobuf {
-namespace descriptor {
-inline upb::reffed_ptr<const upb::SymbolTable> SymbolTable() {
- const upb::SymbolTable* s = upbdefs_google_protobuf_descriptor(&s);
- return upb::reffed_ptr<const upb::SymbolTable>(s, &s);
-}
-} /* namespace descriptor */
-} /* namespace protobuf */
-} /* namespace google */
-#define RETURN_REFFED(type, func) \
- const type* obj = func(upbdefs::google::protobuf::descriptor::SymbolTable().get()); \
- return upb::reffed_ptr<const type>(obj);
+class DescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ DescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace DescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_DescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> enum_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_enum_type) }
-inline upb::reffed_ptr<const upb::FieldDef> extension() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_extension) }
-inline upb::reffed_ptr<const upb::FieldDef> extension_range() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_extension_range) }
-inline upb::reffed_ptr<const upb::FieldDef> field() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_field) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> nested_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_nested_type) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_options) }
-} /* namespace DescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static DescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_DescriptorProto_get(&m);
+ return DescriptorProto(m, &m);
+ }
-namespace google {
-namespace protobuf {
-namespace DescriptorProto {
-namespace ExtensionRange {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_DescriptorProto_ExtensionRange) }
-inline upb::reffed_ptr<const upb::FieldDef> end() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_ExtensionRange_end) }
-inline upb::reffed_ptr<const upb::FieldDef> start() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_DescriptorProto_ExtensionRange_start) }
-} /* namespace ExtensionRange */
-} /* namespace DescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ class ExtensionRange : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ ExtensionRange(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ExtensionRange_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace EnumDescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumDescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumDescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumDescriptorProto_options) }
-inline upb::reffed_ptr<const upb::FieldDef> value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumDescriptorProto_value) }
-} /* namespace EnumDescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static ExtensionRange get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_DescriptorProto_ExtensionRange_get(&m);
+ return ExtensionRange(m, &m);
+ }
+ };
-namespace google {
-namespace protobuf {
-namespace EnumOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> allow_alias() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumOptions_allow_alias) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumOptions_uninterpreted_option) }
-} /* namespace EnumOptions */
-} /* namespace protobuf */
-} /* namespace google */
+ class ReservedRange : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ ReservedRange(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_DescriptorProto_ReservedRange_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace EnumValueDescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumValueDescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueDescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> number() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueDescriptorProto_number) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueDescriptorProto_options) }
-} /* namespace EnumValueDescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static ReservedRange get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_DescriptorProto_ReservedRange_get(&m);
+ return ReservedRange(m, &m);
+ }
+ };
+};
-namespace google {
-namespace protobuf {
-namespace EnumValueOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_EnumValueOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_EnumValueOptions_uninterpreted_option) }
-} /* namespace EnumValueOptions */
-} /* namespace protobuf */
-} /* namespace google */
+class EnumDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ EnumDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_EnumDescriptorProto_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace FieldDescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FieldDescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> default_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_default_value) }
-inline upb::reffed_ptr<const upb::FieldDef> extendee() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_extendee) }
-inline upb::reffed_ptr<const upb::FieldDef> label() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_label) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> number() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_number) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_options) }
-inline upb::reffed_ptr<const upb::FieldDef> type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_type) }
-inline upb::reffed_ptr<const upb::FieldDef> type_name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldDescriptorProto_type_name) }
-inline upb::reffed_ptr<const upb::EnumDef> Label() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FieldDescriptorProto_Label) }
-inline upb::reffed_ptr<const upb::EnumDef> Type() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FieldDescriptorProto_Type) }
-} /* namespace FieldDescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static EnumDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumDescriptorProto_get(&m);
+ return EnumDescriptorProto(m, &m);
+ }
+};
-namespace google {
-namespace protobuf {
-namespace FieldOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FieldOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> ctype() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_ctype) }
-inline upb::reffed_ptr<const upb::FieldDef> deprecated() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_deprecated) }
-inline upb::reffed_ptr<const upb::FieldDef> experimental_map_key() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_experimental_map_key) }
-inline upb::reffed_ptr<const upb::FieldDef> lazy() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_lazy) }
-inline upb::reffed_ptr<const upb::FieldDef> packed() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_packed) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_uninterpreted_option) }
-inline upb::reffed_ptr<const upb::FieldDef> weak() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FieldOptions_weak) }
-inline upb::reffed_ptr<const upb::EnumDef> CType() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FieldOptions_CType) }
-} /* namespace FieldOptions */
-} /* namespace protobuf */
-} /* namespace google */
+class EnumOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ EnumOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_EnumOptions_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace FileDescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FileDescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> dependency() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_dependency) }
-inline upb::reffed_ptr<const upb::FieldDef> enum_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_enum_type) }
-inline upb::reffed_ptr<const upb::FieldDef> extension() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_extension) }
-inline upb::reffed_ptr<const upb::FieldDef> message_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_message_type) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_options) }
-inline upb::reffed_ptr<const upb::FieldDef> package() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_package) }
-inline upb::reffed_ptr<const upb::FieldDef> public_dependency() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_public_dependency) }
-inline upb::reffed_ptr<const upb::FieldDef> service() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_service) }
-inline upb::reffed_ptr<const upb::FieldDef> source_code_info() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_source_code_info) }
-inline upb::reffed_ptr<const upb::FieldDef> weak_dependency() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorProto_weak_dependency) }
-} /* namespace FileDescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static EnumOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumOptions_get(&m);
+ return EnumOptions(m, &m);
+ }
+};
-namespace google {
-namespace protobuf {
-namespace FileDescriptorSet {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FileDescriptorSet) }
-inline upb::reffed_ptr<const upb::FieldDef> file() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileDescriptorSet_file) }
-} /* namespace FileDescriptorSet */
-} /* namespace protobuf */
-} /* namespace google */
+class EnumValueDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ EnumValueDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_EnumValueDescriptorProto_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace FileOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_FileOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> cc_generic_services() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_cc_generic_services) }
-inline upb::reffed_ptr<const upb::FieldDef> go_package() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_go_package) }
-inline upb::reffed_ptr<const upb::FieldDef> java_generate_equals_and_hash() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_generate_equals_and_hash) }
-inline upb::reffed_ptr<const upb::FieldDef> java_generic_services() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_generic_services) }
-inline upb::reffed_ptr<const upb::FieldDef> java_multiple_files() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_multiple_files) }
-inline upb::reffed_ptr<const upb::FieldDef> java_outer_classname() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_outer_classname) }
-inline upb::reffed_ptr<const upb::FieldDef> java_package() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_java_package) }
-inline upb::reffed_ptr<const upb::FieldDef> optimize_for() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_optimize_for) }
-inline upb::reffed_ptr<const upb::FieldDef> py_generic_services() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_py_generic_services) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_FileOptions_uninterpreted_option) }
-inline upb::reffed_ptr<const upb::EnumDef> OptimizeMode() { RETURN_REFFED(upb::EnumDef, upbdefs_google_protobuf_FileOptions_OptimizeMode) }
-} /* namespace FileOptions */
-} /* namespace protobuf */
-} /* namespace google */
+ static EnumValueDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumValueDescriptorProto_get(&m);
+ return EnumValueDescriptorProto(m, &m);
+ }
+};
-namespace google {
-namespace protobuf {
-namespace MessageOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_MessageOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> message_set_wire_format() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MessageOptions_message_set_wire_format) }
-inline upb::reffed_ptr<const upb::FieldDef> no_standard_descriptor_accessor() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MessageOptions_no_standard_descriptor_accessor) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MessageOptions_uninterpreted_option) }
-} /* namespace MessageOptions */
-} /* namespace protobuf */
-} /* namespace google */
+class EnumValueOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ EnumValueOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_EnumValueOptions_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace MethodDescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_MethodDescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> input_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_input_type) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_options) }
-inline upb::reffed_ptr<const upb::FieldDef> output_type() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodDescriptorProto_output_type) }
-} /* namespace MethodDescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static EnumValueOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_EnumValueOptions_get(&m);
+ return EnumValueOptions(m, &m);
+ }
+};
-namespace google {
-namespace protobuf {
-namespace MethodOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_MethodOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_MethodOptions_uninterpreted_option) }
-} /* namespace MethodOptions */
-} /* namespace protobuf */
-} /* namespace google */
+class FieldDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ FieldDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace ServiceDescriptorProto {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_ServiceDescriptorProto) }
-inline upb::reffed_ptr<const upb::FieldDef> method() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceDescriptorProto_method) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceDescriptorProto_name) }
-inline upb::reffed_ptr<const upb::FieldDef> options() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceDescriptorProto_options) }
-} /* namespace ServiceDescriptorProto */
-} /* namespace protobuf */
-} /* namespace google */
+ static FieldDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_FieldDescriptorProto_get(&m);
+ return FieldDescriptorProto(m, &m);
+ }
-namespace google {
-namespace protobuf {
-namespace ServiceOptions {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_ServiceOptions) }
-inline upb::reffed_ptr<const upb::FieldDef> uninterpreted_option() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_ServiceOptions_uninterpreted_option) }
-} /* namespace ServiceOptions */
-} /* namespace protobuf */
-} /* namespace google */
+ class Label : public ::upb::reffed_ptr<const ::upb::EnumDef> {
+ public:
+ Label(const ::upb::EnumDef* e, const void *ref_donor = NULL)
+ : reffed_ptr(e, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_Label_is(e));
+ }
+ static Label get() {
+ const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldDescriptorProto_Label_get(&e);
+ return Label(e, &e);
+ }
+ };
-namespace google {
-namespace protobuf {
-namespace SourceCodeInfo {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_SourceCodeInfo) }
-inline upb::reffed_ptr<const upb::FieldDef> location() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_location) }
-} /* namespace SourceCodeInfo */
-} /* namespace protobuf */
-} /* namespace google */
+ class Type : public ::upb::reffed_ptr<const ::upb::EnumDef> {
+ public:
+ Type(const ::upb::EnumDef* e, const void *ref_donor = NULL)
+ : reffed_ptr(e, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FieldDescriptorProto_Type_is(e));
+ }
+ static Type get() {
+ const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldDescriptorProto_Type_get(&e);
+ return Type(e, &e);
+ }
+ };
+};
-namespace google {
-namespace protobuf {
-namespace SourceCodeInfo {
-namespace Location {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_SourceCodeInfo_Location) }
-inline upb::reffed_ptr<const upb::FieldDef> leading_comments() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_leading_comments) }
-inline upb::reffed_ptr<const upb::FieldDef> path() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_path) }
-inline upb::reffed_ptr<const upb::FieldDef> span() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_span) }
-inline upb::reffed_ptr<const upb::FieldDef> trailing_comments() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_SourceCodeInfo_Location_trailing_comments) }
-} /* namespace Location */
-} /* namespace SourceCodeInfo */
-} /* namespace protobuf */
-} /* namespace google */
+class FieldOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ FieldOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_is(m));
+ }
-namespace google {
-namespace protobuf {
-namespace UninterpretedOption {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_UninterpretedOption) }
-inline upb::reffed_ptr<const upb::FieldDef> aggregate_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_aggregate_value) }
-inline upb::reffed_ptr<const upb::FieldDef> double_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_double_value) }
-inline upb::reffed_ptr<const upb::FieldDef> identifier_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_identifier_value) }
-inline upb::reffed_ptr<const upb::FieldDef> name() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_name) }
-inline upb::reffed_ptr<const upb::FieldDef> negative_int_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_negative_int_value) }
-inline upb::reffed_ptr<const upb::FieldDef> positive_int_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_positive_int_value) }
-inline upb::reffed_ptr<const upb::FieldDef> string_value() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_string_value) }
-} /* namespace UninterpretedOption */
-} /* namespace protobuf */
-} /* namespace google */
+ static FieldOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_FieldOptions_get(&m);
+ return FieldOptions(m, &m);
+ }
+
+ class CType : public ::upb::reffed_ptr<const ::upb::EnumDef> {
+ public:
+ CType(const ::upb::EnumDef* e, const void *ref_donor = NULL)
+ : reffed_ptr(e, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_CType_is(e));
+ }
+ static CType get() {
+ const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldOptions_CType_get(&e);
+ return CType(e, &e);
+ }
+ };
+
+ class JSType : public ::upb::reffed_ptr<const ::upb::EnumDef> {
+ public:
+ JSType(const ::upb::EnumDef* e, const void *ref_donor = NULL)
+ : reffed_ptr(e, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FieldOptions_JSType_is(e));
+ }
+ static JSType get() {
+ const ::upb::EnumDef* e = upbdefs_google_protobuf_FieldOptions_JSType_get(&e);
+ return JSType(e, &e);
+ }
+ };
+};
+
+class FileDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ FileDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorProto_is(m));
+ }
+
+ static FileDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_FileDescriptorProto_get(&m);
+ return FileDescriptorProto(m, &m);
+ }
+};
+
+class FileDescriptorSet : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ FileDescriptorSet(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FileDescriptorSet_is(m));
+ }
+
+ static FileDescriptorSet get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_FileDescriptorSet_get(&m);
+ return FileDescriptorSet(m, &m);
+ }
+};
+
+class FileOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ FileOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FileOptions_is(m));
+ }
+
+ static FileOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_FileOptions_get(&m);
+ return FileOptions(m, &m);
+ }
+
+ class OptimizeMode : public ::upb::reffed_ptr<const ::upb::EnumDef> {
+ public:
+ OptimizeMode(const ::upb::EnumDef* e, const void *ref_donor = NULL)
+ : reffed_ptr(e, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_FileOptions_OptimizeMode_is(e));
+ }
+ static OptimizeMode get() {
+ const ::upb::EnumDef* e = upbdefs_google_protobuf_FileOptions_OptimizeMode_get(&e);
+ return OptimizeMode(e, &e);
+ }
+ };
+};
+
+class MessageOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ MessageOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_MessageOptions_is(m));
+ }
+
+ static MessageOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_MessageOptions_get(&m);
+ return MessageOptions(m, &m);
+ }
+};
+
+class MethodDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ MethodDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_MethodDescriptorProto_is(m));
+ }
+
+ static MethodDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_MethodDescriptorProto_get(&m);
+ return MethodDescriptorProto(m, &m);
+ }
+};
+
+class MethodOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ MethodOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_MethodOptions_is(m));
+ }
+
+ static MethodOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_MethodOptions_get(&m);
+ return MethodOptions(m, &m);
+ }
+};
+
+class OneofDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ OneofDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_OneofDescriptorProto_is(m));
+ }
+
+ static OneofDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_OneofDescriptorProto_get(&m);
+ return OneofDescriptorProto(m, &m);
+ }
+};
+
+class ServiceDescriptorProto : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ ServiceDescriptorProto(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_ServiceDescriptorProto_is(m));
+ }
+
+ static ServiceDescriptorProto get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_ServiceDescriptorProto_get(&m);
+ return ServiceDescriptorProto(m, &m);
+ }
+};
+
+class ServiceOptions : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ ServiceOptions(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_ServiceOptions_is(m));
+ }
+
+ static ServiceOptions get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_ServiceOptions_get(&m);
+ return ServiceOptions(m, &m);
+ }
+};
+
+class SourceCodeInfo : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ SourceCodeInfo(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_is(m));
+ }
+
+ static SourceCodeInfo get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_SourceCodeInfo_get(&m);
+ return SourceCodeInfo(m, &m);
+ }
+
+ class Location : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ Location(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_SourceCodeInfo_Location_is(m));
+ }
+
+ static Location get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_SourceCodeInfo_Location_get(&m);
+ return Location(m, &m);
+ }
+ };
+};
+
+class UninterpretedOption : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ UninterpretedOption(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_is(m));
+ }
+
+ static UninterpretedOption get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_UninterpretedOption_get(&m);
+ return UninterpretedOption(m, &m);
+ }
+
+ class NamePart : public ::upb::reffed_ptr<const ::upb::MessageDef> {
+ public:
+ NamePart(const ::upb::MessageDef* m, const void *ref_donor = NULL)
+ : reffed_ptr(m, ref_donor) {
+ UPB_ASSERT(upbdefs_google_protobuf_UninterpretedOption_NamePart_is(m));
+ }
+
+ static NamePart get() {
+ const ::upb::MessageDef* m = upbdefs_google_protobuf_UninterpretedOption_NamePart_get(&m);
+ return NamePart(m, &m);
+ }
+ };
+};
-namespace google {
-namespace protobuf {
-namespace UninterpretedOption {
-namespace NamePart {
-inline upb::reffed_ptr<const upb::MessageDef> MessageDef() { RETURN_REFFED(upb::MessageDef, upbdefs_google_protobuf_UninterpretedOption_NamePart) }
-inline upb::reffed_ptr<const upb::FieldDef> is_extension() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_NamePart_is_extension) }
-inline upb::reffed_ptr<const upb::FieldDef> name_part() { RETURN_REFFED(upb::FieldDef, upbdefs_google_protobuf_UninterpretedOption_NamePart_name_part) }
-} /* namespace NamePart */
-} /* namespace UninterpretedOption */
} /* namespace protobuf */
} /* namespace google */
-
} /* namespace upbdefs */
+#endif /* __cplusplus */
-#undef RETURN_REFFED
-#endif /* __cplusplus */
-
-#endif /* GOOGLE_PROTOBUF_DESCRIPTOR_UPB_H_ */
+#endif /* UPB_DESCRIPTOR_DESCRIPTOR_PROTO_UPB_H_ */
/*
** Internal-only definitions for the decoder.
*/
@@ -7030,7 +7339,6 @@ inline upb::reffed_ptr<const upb::FieldDef> name_part() { RETURN_REFFED(upb::Fie
#ifndef UPB_DECODER_INT_H_
#define UPB_DECODER_INT_H_
-#include <stdlib.h>
/*
** upb::pb::Decoder
**
@@ -7067,6 +7375,13 @@ UPB_DECLARE_TYPE(upb::pb::DecoderMethodOptions, upb_pbdecodermethodopts)
UPB_DECLARE_DERIVED_TYPE(upb::pb::DecoderMethod, upb::RefCounted,
upb_pbdecodermethod, upb_refcounted)
+/* The maximum number of bytes we are required to buffer internally between
+ * calls to the decoder. The value is 14: a 5 byte unknown tag plus ten-byte
+ * varint, less one because we are buffering an incomplete value.
+ *
+ * Should only be used by unit tests. */
+#define UPB_DECODER_MAX_RESIDUAL_BYTES 14
+
#ifdef __cplusplus
/* The parameters one uses to construct a DecoderMethod.
@@ -7123,7 +7438,7 @@ class upb::pb::DecoderMethod {
* constructed. This hint may be an overestimate for some build configurations.
* But if the decoder library is upgraded without recompiling the application,
* it may be an underestimate. */
-#define UPB_PB_DECODER_SIZE 4408
+#define UPB_PB_DECODER_SIZE 4416
#ifdef __cplusplus
@@ -7541,11 +7856,8 @@ struct upb_pbdecoder {
/* Overall stream offset of "buf." */
uint64_t bufstart_ofs;
- /* Buffer for residual bytes not parsed from the previous buffer.
- * The maximum number of residual bytes we require is 12; a five-byte
- * unknown tag plus an eight-byte value, less one because the value
- * is only a partial value. */
- char residual[12];
+ /* Buffer for residual bytes not parsed from the previous buffer. */
+ char residual[UPB_DECODER_MAX_RESIDUAL_BYTES];
char *residual_end;
/* Bytes of data that should be discarded from the input beore we start
@@ -7812,9 +8124,9 @@ UPB_INLINE uint64_t upb_vencode32(uint32_t val) {
char buf[UPB_PB_VARINT_MAX_LEN];
size_t bytes = upb_vencode64(val, buf);
uint64_t ret = 0;
- assert(bytes <= 5);
+ UPB_ASSERT(bytes <= 5);
memcpy(&ret, buf, bytes);
- assert(ret <= 0xffffffffffU);
+ UPB_ASSERT(ret <= 0xffffffffffU);
return ret;
}
@@ -7939,49 +8251,44 @@ inline reffed_ptr<const Handlers> Encoder::NewHandlers(
#include <stdbool.h>
#ifdef __cplusplus
+#include <vector>
+
extern "C" {
#endif
-/* Loads all defs from the given protobuf binary descriptor, setting default
- * accessors and a default layout on all messages. The caller owns the
- * returned array of defs, which will be of length *n. On error NULL is
- * returned and status is set (if non-NULL). */
-upb_def **upb_load_defs_from_descriptor(const char *str, size_t len, int *n,
- void *owner, upb_status *status);
-
-/* Like the previous but also adds the loaded defs to the given symtab. */
-bool upb_load_descriptor_into_symtab(upb_symtab *symtab, const char *str,
- size_t len, upb_status *status);
-
-/* Like the previous but also reads the descriptor from the given filename. */
-bool upb_load_descriptor_file_into_symtab(upb_symtab *symtab, const char *fname,
- upb_status *status);
-
-/* Reads the given filename into a character string, returning NULL if there
- * was an error. */
-char *upb_readfile(const char *filename, size_t *len);
+/* Loads a binary descriptor and returns a NULL-terminated array of unfrozen
+ * filedefs. The caller owns the returned array, which must be freed with
+ * upb_gfree(). */
+upb_filedef **upb_loaddescriptor(const char *buf, size_t n, const void *owner,
+ upb_status *status);
#ifdef __cplusplus
} /* extern "C" */
namespace upb {
-/* All routines that load descriptors expect the descriptor to be a
- * FileDescriptorSet. */
-inline bool LoadDescriptorFileIntoSymtab(SymbolTable* s, const char *fname,
- Status* status) {
- return upb_load_descriptor_file_into_symtab(s, fname, status);
-}
+inline bool LoadDescriptor(const char* buf, size_t n, Status* status,
+ std::vector<reffed_ptr<FileDef> >* files) {
+ FileDef** parsed_files = upb_loaddescriptor(buf, n, &parsed_files, status);
-inline bool LoadDescriptorIntoSymtab(SymbolTable* s, const char* str,
- size_t len, Status* status) {
- return upb_load_descriptor_into_symtab(s, str, len, status);
+ if (parsed_files) {
+ FileDef** p = parsed_files;
+ while (*p) {
+ files->push_back(reffed_ptr<FileDef>(*p, &parsed_files));
+ ++p;
+ }
+ free(parsed_files);
+ return true;
+ } else {
+ return false;
+ }
}
/* Templated so it can accept both string and std::string. */
template <typename T>
-bool LoadDescriptorIntoSymtab(SymbolTable* s, const T& desc, Status* status) {
- return upb_load_descriptor_into_symtab(s, desc.c_str(), desc.size(), status);
+bool LoadDescriptor(const T& desc, Status* status,
+ std::vector<reffed_ptr<FileDef> >* files) {
+ return LoadDescriptor(desc.c_str(), desc.size(), status, files);
}
} /* namespace upb */
@@ -8083,11 +8390,14 @@ inline reffed_ptr<const Handlers> TextPrinter::NewHandlers(
namespace upb {
namespace json {
class Parser;
+class ParserMethod;
} /* namespace json */
} /* namespace upb */
#endif
UPB_DECLARE_TYPE(upb::json::Parser, upb_json_parser)
+UPB_DECLARE_DERIVED_TYPE(upb::json::ParserMethod, upb::RefCounted,
+ upb_json_parsermethod, upb_refcounted)
/* upb::json::Parser **********************************************************/
@@ -8095,7 +8405,7 @@ UPB_DECLARE_TYPE(upb::json::Parser, upb_json_parser)
* constructed. This hint may be an overestimate for some build configurations.
* But if the parser library is upgraded without recompiling the application,
* it may be an underestimate. */
-#define UPB_JSON_PARSER_SIZE 3704
+#define UPB_JSON_PARSER_SIZE 4112
#ifdef __cplusplus
@@ -8103,7 +8413,8 @@ UPB_DECLARE_TYPE(upb::json::Parser, upb_json_parser)
* sink. */
class upb::json::Parser {
public:
- static Parser* Create(Environment* env, Sink* output);
+ static Parser* Create(Environment* env, const ParserMethod* method,
+ Sink* output);
BytesSink* input();
@@ -8111,25 +8422,72 @@ class upb::json::Parser {
UPB_DISALLOW_POD_OPS(Parser, upb::json::Parser)
};
+class upb::json::ParserMethod {
+ public:
+ /* Include base methods from upb::ReferenceCounted. */
+ UPB_REFCOUNTED_CPPMETHODS
+
+ /* Returns handlers for parsing according to the specified schema. */
+ static reffed_ptr<const ParserMethod> New(const upb::MessageDef* md);
+
+ /* The destination handlers that are statically bound to this method.
+ * This method is only capable of outputting to a sink that uses these
+ * handlers. */
+ const Handlers* dest_handlers() const;
+
+ /* The input handlers for this decoder method. */
+ const BytesHandler* input_handler() const;
+
+ private:
+ UPB_DISALLOW_POD_OPS(ParserMethod, upb::json::ParserMethod)
+};
+
#endif
UPB_BEGIN_EXTERN_C
-upb_json_parser *upb_json_parser_create(upb_env *e, upb_sink *output);
+upb_json_parser* upb_json_parser_create(upb_env* e,
+ const upb_json_parsermethod* m,
+ upb_sink* output);
upb_bytessink *upb_json_parser_input(upb_json_parser *p);
+upb_json_parsermethod* upb_json_parsermethod_new(const upb_msgdef* md,
+ const void* owner);
+const upb_handlers *upb_json_parsermethod_desthandlers(
+ const upb_json_parsermethod *m);
+const upb_byteshandler *upb_json_parsermethod_inputhandler(
+ const upb_json_parsermethod *m);
+
+/* Include refcounted methods like upb_json_parsermethod_ref(). */
+UPB_REFCOUNTED_CMETHODS(upb_json_parsermethod, upb_json_parsermethod_upcast)
+
UPB_END_EXTERN_C
#ifdef __cplusplus
namespace upb {
namespace json {
-inline Parser* Parser::Create(Environment* env, Sink* output) {
- return upb_json_parser_create(env, output);
+inline Parser* Parser::Create(Environment* env, const ParserMethod* method,
+ Sink* output) {
+ return upb_json_parser_create(env, method, output);
}
inline BytesSink* Parser::input() {
return upb_json_parser_input(this);
}
+
+inline const Handlers* ParserMethod::dest_handlers() const {
+ return upb_json_parsermethod_desthandlers(this);
+}
+inline const BytesHandler* ParserMethod::input_handler() const {
+ return upb_json_parsermethod_inputhandler(this);
+}
+/* static */
+inline reffed_ptr<const ParserMethod> ParserMethod::New(
+ const MessageDef* md) {
+ const upb_json_parsermethod *m = upb_json_parsermethod_new(md, &m);
+ return reffed_ptr<const ParserMethod>(m, &m);
+}
+
} /* namespace json */
} /* namespace upb */
@@ -8160,7 +8518,7 @@ UPB_DECLARE_TYPE(upb::json::Printer, upb_json_printer)
/* upb::json::Printer *********************************************************/
-#define UPB_JSON_PRINTER_SIZE 168
+#define UPB_JSON_PRINTER_SIZE 176
#ifdef __cplusplus
@@ -8173,8 +8531,12 @@ class upb::json::Printer {
/* The input to the printer. */
Sink* input();
- /* Returns handlers for printing according to the specified schema. */
- static reffed_ptr<const Handlers> NewHandlers(const upb::MessageDef* md);
+ /* Returns handlers for printing according to the specified schema.
+ * If preserve_proto_fieldnames is true, the output JSON will use the
+ * original .proto field names (ie. {"my_field":3}) instead of using
+ * camelCased names, which is the default: (eg. {"myField":3}). */
+ static reffed_ptr<const Handlers> NewHandlers(const upb::MessageDef* md,
+ bool preserve_proto_fieldnames);
static const size_t kSize = UPB_JSON_PRINTER_SIZE;
@@ -8191,6 +8553,7 @@ upb_json_printer *upb_json_printer_create(upb_env *e, const upb_handlers *h,
upb_bytessink *output);
upb_sink *upb_json_printer_input(upb_json_printer *p);
const upb_handlers *upb_json_printer_newhandlers(const upb_msgdef *md,
+ bool preserve_fieldnames,
const void *owner);
UPB_END_EXTERN_C
@@ -8205,8 +8568,9 @@ inline Printer* Printer::Create(Environment* env, const upb::Handlers* handlers,
}
inline Sink* Printer::input() { return upb_json_printer_input(this); }
inline reffed_ptr<const Handlers> Printer::NewHandlers(
- const upb::MessageDef *md) {
- const Handlers* h = upb_json_printer_newhandlers(md, &h);
+ const upb::MessageDef *md, bool preserve_proto_fieldnames) {
+ const Handlers* h = upb_json_printer_newhandlers(
+ md, preserve_proto_fieldnames, &h);
return reffed_ptr<const Handlers>(h, &h);
}
} /* namespace json */
diff --git a/php/ext/google/protobuf/utf8.c b/php/ext/google/protobuf/utf8.c
new file mode 100644
index 00000000..2752a08b
--- /dev/null
+++ b/php/ext/google/protobuf/utf8.c
@@ -0,0 +1,68 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#include "utf8.h"
+
+static const uint8_t utf8_offset[] = {
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+ 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0,
+};
+
+bool is_structurally_valid_utf8(const char* buf, int len) {
+ int i, j;
+ uint8_t offset;
+
+ i = 0;
+ while (i < len) {
+ offset = utf8_offset[(uint8_t)buf[i]];
+ if (offset == 0 || i + offset > len) {
+ return false;
+ }
+ for (j = i + 1; j < i + offset; j++) {
+ if ((buf[j] & 0xc0) != 0x80) {
+ return false;
+ }
+ }
+ i += offset;
+ }
+ return i == len;
+}
diff --git a/php/ext/google/protobuf/utf8.h b/php/ext/google/protobuf/utf8.h
new file mode 100644
index 00000000..28b8d874
--- /dev/null
+++ b/php/ext/google/protobuf/utf8.h
@@ -0,0 +1,36 @@
+// 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_UTF8_H_
+#define GOOGLE_PROTOBUF_UTF8_H_
+
+bool is_structurally_valid_utf8(const char* buf, int len);
+
+#endif // GOOGLE_PROTOBUF_UTF8_H_
diff --git a/php/src/Google/Protobuf/Internal/DescriptorPool.php b/php/src/Google/Protobuf/Internal/DescriptorPool.php
new file mode 100644
index 00000000..23b304ac
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/DescriptorPool.php
@@ -0,0 +1,162 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\Descriptor;
+use Google\Protobuf\Internal\FileDescriptor;
+use Google\Protobuf\Internal\FileDescriptorSet;
+use Google\Protobuf\Internal\MessageBuilderContext;
+use Google\Protobuf\Internal\EnumBuilderContext;
+
+class DescriptorPool
+{
+ private static $pool;
+ // Map from message names to sub-maps, which are maps from field numbers to
+ // field descriptors.
+ private $class_to_desc = [];
+ private $class_to_enum_desc = [];
+ private $proto_to_class = [];
+
+ public static function getGeneratedPool()
+ {
+ if (!isset(self::$pool)) {
+ self::$pool = new DescriptorPool();
+ }
+ return self::$pool;
+ }
+
+ public function internalAddGeneratedFile($data)
+ {
+ $files = new FileDescriptorSet();
+ $files->decode($data);
+ $file = FileDescriptor::buildFromProto($files->getFile()[0]);
+
+ foreach ($file->getMessageType() as &$desc) {
+ $this->addDescriptor($desc);
+ }
+ unset($desc);
+
+ foreach ($file->getEnumType() as &$desc) {
+ $this->addEnumDescriptor($desc);
+ }
+ unset($desc);
+
+ foreach ($file->getMessageType() as &$desc) {
+ $this->crossLink($desc);
+ }
+ unset($desc);
+ }
+
+ public function addMessage($name, $klass)
+ {
+ return new MessageBuilderContext($name, $klass, $this);
+ }
+
+ public function addEnum($name, $klass)
+ {
+ return new EnumBuilderContext($name, $klass, $this);
+ }
+
+ public function addDescriptor($descriptor)
+ {
+ $this->proto_to_class[$descriptor->getFullName()] =
+ $descriptor->getClass();
+ $this->class_to_desc[$descriptor->getClass()] = $descriptor;
+ foreach ($descriptor->getNestedType() as $nested_type) {
+ $this->addDescriptor($nested_type);
+ }
+ }
+
+ public function addEnumDescriptor($descriptor)
+ {
+ $this->proto_to_class[$descriptor->getFullName()] =
+ $descriptor->getClass();
+ $this->class_to_enum_desc[$descriptor->getClass()] = $descriptor;
+ }
+
+ public function getDescriptorByClassName($klass)
+ {
+ return $this->class_to_desc[$klass];
+ }
+
+ public function getEnumDescriptorByClassName($klass)
+ {
+ return $this->class_to_enum_desc[$klass];
+ }
+
+ public function getDescriptorByProtoName($proto)
+ {
+ $klass = $this->proto_to_class[$proto];
+ return $this->class_to_desc[$klass];
+ }
+
+ public function getEnumDescriptorByProtoName($proto)
+ {
+ $klass = $this->proto_to_class[$proto];
+ return $this->class_to_enum_desc[$klass];
+ }
+
+ private function crossLink(&$desc)
+ {
+ foreach ($desc->getField() as &$field) {
+ switch ($field->getType()) {
+ case GPBType::MESSAGE:
+ $proto = $field->getMessageType();
+ $field->setMessageType(
+ $this->getDescriptorByProtoName($proto));
+ break;
+ case GPBType::ENUM:
+ $proto = $field->getEnumType();
+ $field->setEnumType(
+ $this->getEnumDescriptorByProtoName($proto));
+ break;
+ default:
+ break;
+ }
+ }
+ unset($field);
+
+ foreach ($desc->getNestedType() as &$nested_type) {
+ $this->crossLink($nested_type);
+ }
+ unset($nested_type);
+ }
+
+ public function finish()
+ {
+ foreach ($this->class_to_desc as $klass => &$desc) {
+ $this->crossLink($desc);
+ }
+ unset($desc);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/EnumBuilderContext.php b/php/src/Google/Protobuf/Internal/EnumBuilderContext.php
new file mode 100644
index 00000000..c1dac24d
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/EnumBuilderContext.php
@@ -0,0 +1,63 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\EnumDescriptor;
+use Google\Protobuf\Internal\EnumValueDescriptor;
+
+class EnumBuilderContext
+{
+
+ private $descriptor;
+ private $pool;
+
+ public function __construct($full_name, $klass, $pool)
+ {
+ $this->descriptor = new EnumDescriptor();
+ $this->descriptor->setFullName($full_name);
+ $this->descriptor->setClass($klass);
+ $this->pool = $pool;
+ }
+
+ public function value($name, $number)
+ {
+ $value = new EnumValueDescriptor();
+ $this->descriptor->addValue($number, $value);
+ return $this;
+ }
+
+ public function finalizeToPool()
+ {
+ $this->pool->addEnumDescriptor($this->descriptor);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/GPBLabel.php b/php/src/Google/Protobuf/Internal/GPBLabel.php
new file mode 100644
index 00000000..0fb23841
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBLabel.php
@@ -0,0 +1,40 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+class GPBLabel
+{
+ const OPTIONAL = 1;
+ const REQUIRED = 2;
+ const REPEATED = 3;
+}
diff --git a/php/src/Google/Protobuf/Internal/GPBType.php b/php/src/Google/Protobuf/Internal/GPBType.php
new file mode 100644
index 00000000..fa849ceb
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBType.php
@@ -0,0 +1,55 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+class GPBType
+{
+ const DOUBLE = 1;
+ const FLOAT = 2;
+ const INT64 = 3;
+ const UINT64 = 4;
+ const INT32 = 5;
+ const FIXED64 = 6;
+ const FIXED32 = 7;
+ const BOOL = 8;
+ const STRING = 9;
+ const GROUP = 10;
+ const MESSAGE = 11;
+ const BYTES = 12;
+ const UINT32 = 13;
+ const ENUM = 14;
+ const SFIXED32 = 15;
+ const SFIXED64 = 16;
+ const SINT32 = 17;
+ const SINT64 = 18;
+}
diff --git a/php/src/Google/Protobuf/Internal/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php
new file mode 100644
index 00000000..30d7350f
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBUtil.php
@@ -0,0 +1,196 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+
+class GPBUtil
+{
+ public function divideInt64ToInt32($value, &$high, &$low, $trim = false)
+ {
+ $isNeg = (bccomp($value, 0) < 0);
+ if ($isNeg) {
+ $value = bcsub(0, $value);
+ }
+ $high = (int) bcdiv(bcadd($value, 1), 4294967296);
+ $low = (int) bcmod($value, 4294967296);
+ if ($isNeg) {
+ $high = ~$high;
+ $low = ~$low;
+ $low++;
+ if (!$low) {
+ $high++;
+ }
+ }
+
+ if ($trim) {
+ $high = 0;
+ }
+ }
+
+
+ public static function checkString(&$var, $check_utf8)
+ {
+ if (is_array($var) || is_object($var)) {
+ trigger_error("Expect string.", E_USER_ERROR);
+ return;
+ }
+ if (!is_string($var)) {
+ $var = strval($var);
+ }
+ if ($check_utf8 && !preg_match('//u', $var)) {
+ trigger_error("Expect utf-8 encoding.", E_USER_ERROR);
+ return;
+ }
+ }
+
+ public static function checkEnum(&$var)
+ {
+ static::checkInt32($var);
+ }
+
+ public static function checkInt32(&$var)
+ {
+ if (is_numeric($var)) {
+ $var = intval($var);
+ } else {
+ trigger_error("Expect integer.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkUint32(&$var)
+ {
+ if (is_numeric($var)) {
+ if (PHP_INT_SIZE === 8) {
+ $var = intval($var);
+ $var |= ((-(($var >> 31) & 0x1)) & ~0xFFFFFFFF);
+ } else {
+ if (bccomp($var, 0x7FFFFFFF) > 0) {
+ $var = bcsub($var, "4294967296");
+ }
+ $var = (int) $var;
+ }
+ } else {
+ trigger_error("Expect integer.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkInt64(&$var)
+ {
+ if (is_numeric($var)) {
+ if (PHP_INT_SIZE == 8) {
+ $var = intval($var);
+ } else {
+ $var = bcdiv($var, 1, 0);
+ }
+ } else {
+ trigger_error("Expect integer.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkUint64(&$var)
+ {
+ if (is_numeric($var)) {
+ if (PHP_INT_SIZE == 8) {
+ $var = intval($var);
+ } else {
+ $var = bcdiv($var, 1, 0);
+ }
+ } else {
+ trigger_error("Expect integer.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkFloat(&$var)
+ {
+ if (is_float($var) || is_numeric($var)) {
+ $var = floatval($var);
+ } else {
+ trigger_error("Expect float.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkDouble(&$var)
+ {
+ if (is_float($var) || is_numeric($var)) {
+ $var = floatval($var);
+ } else {
+ trigger_error("Expect float.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkBool(&$var)
+ {
+ if (is_array($var) || is_object($var)) {
+ trigger_error("Expect boolean.", E_USER_ERROR);
+ return;
+ }
+ $var = boolval($var);
+ }
+
+ public static function checkMessage(&$var, $klass)
+ {
+ if (!$var instanceof $klass && !is_null($var)) {
+ trigger_error("Expect message.", E_USER_ERROR);
+ }
+ }
+
+ public static function checkRepeatedField(&$var, $type, $klass = null)
+ {
+ if (!$var instanceof RepeatedField) {
+ trigger_error("Expect repeated field.", E_USER_ERROR);
+ }
+ if ($var->getType() != $type) {
+ trigger_error(
+ "Expect repeated field of different type.",
+ E_USER_ERROR);
+ }
+ if ($var->getType() === GPBType::MESSAGE &&
+ $var->getClass() !== $klass) {
+ trigger_error(
+ "Expect repeated field of different message.",
+ E_USER_ERROR);
+ }
+ }
+
+ public static function Int64($value)
+ {
+ return new Int64($value);
+ }
+
+ public static function Uint64($value)
+ {
+ return new Uint64($value);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/GPBWire.php b/php/src/Google/Protobuf/Internal/GPBWire.php
new file mode 100644
index 00000000..7e2c124f
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/GPBWire.php
@@ -0,0 +1,582 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+class GPBWire
+{
+
+ const TAG_TYPE_BITS = 3;
+
+ const WIRETYPE_VARINT = 0;
+ const WIRETYPE_FIXED64 = 1;
+ const WIRETYPE_LENGTH_DELIMITED = 2;
+ const WIRETYPE_START_GROUP = 3;
+ const WIRETYPE_END_GROUP = 4;
+ const WIRETYPE_FIXED32 = 5;
+
+ const UNKNOWN = 0;
+ const NORMAL_FORMAT = 1;
+ const PACKED_FORMAT = 2;
+
+ public static function getTagFieldNumber($tag)
+ {
+ return ($tag >> self::TAG_TYPE_BITS) &
+ (1 << ((PHP_INT_SIZE * 8) - self::TAG_TYPE_BITS)) - 1;
+ }
+
+ public static function getTagWireType($tag)
+ {
+ return $tag & 0x7;
+ }
+
+ public static function getWireType($type)
+ {
+ switch ($type) {
+ case GPBType::FLOAT:
+ case GPBType::FIXED32:
+ case GPBType::SFIXED32:
+ return self::WIRETYPE_FIXED32;
+ case GPBType::DOUBLE:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED64:
+ return self::WIRETYPE_FIXED64;
+ case GPBType::UINT32:
+ case GPBType::UINT64:
+ case GPBType::INT32:
+ case GPBType::INT64:
+ case GPBType::SINT32:
+ case GPBType::SINT64:
+ case GPBType::ENUM:
+ case GPBType::BOOL:
+ return self::WIRETYPE_VARINT;
+ case GPBType::STRING:
+ case GPBType::BYTES:
+ case GPBType::MESSAGE:
+ return self::WIRETYPE_LENGTH_DELIMITED;
+ case GPBType::GROUP:
+ user_error("Unsupported type.");
+ return 0;
+ default:
+ user_error("Unsupported type.");
+ return 0;
+ }
+ }
+
+ // ZigZag Transform: Encodes signed integers so that they can be effectively
+ // used with varint encoding.
+ //
+ // varint operates on unsigned integers, encoding smaller numbers into fewer
+ // bytes. If you try to use it on a signed integer, it will treat this
+ // number as a very large unsigned integer, which means that even small
+ // signed numbers like -1 will take the maximum number of bytes (10) to
+ // encode. zigZagEncode() maps signed integers to unsigned in such a way
+ // that those with a small absolute value will have smaller encoded values,
+ // making them appropriate for encoding using varint.
+ //
+ // int32 -> uint32
+ // -------------------------
+ // 0 -> 0
+ // -1 -> 1
+ // 1 -> 2
+ // -2 -> 3
+ // ... -> ...
+ // 2147483647 -> 4294967294
+ // -2147483648 -> 4294967295
+ //
+ // >> encode >>
+ // << decode <<
+ public static function zigZagEncode32($int32)
+ {
+ // Fill high 32 bits.
+ if (PHP_INT_SIZE === 8) {
+ $int32 |= ((($int32 << 32) >> 31) & (0xFFFFFFFF << 32));
+ }
+
+ $uint32 = ($int32 << 1) ^ ($int32 >> 31);
+
+ // Fill high 32 bits.
+ if (PHP_INT_SIZE === 8) {
+ $uint32 |= ((($uint32 << 32) >> 31) & (0xFFFFFFFF << 32));
+ }
+
+ return $uint32;
+ }
+
+ public static function zigZagDecode32($uint32)
+ {
+ // Fill high 32 bits.
+ if (PHP_INT_SIZE === 8) {
+ $uint32 |= ($uint32 & 0xFFFFFFFF);
+ }
+
+ $int32 = (($uint32 >> 1) & 0x7FFFFFFF) ^ (-($uint32 & 1));
+
+ return $int32;
+ }
+
+ public static function zigZagEncode64($int64)
+ {
+ if (PHP_INT_SIZE == 4) {
+ if (bccomp($int64, 0) >= 0) {
+ return bcmul($int64, 2);
+ } else {
+ return bcsub(bcmul(bcsub(0, $int64), 2), 1);
+ }
+ } else {
+ return ($int64 << 1) ^ ($int64 >> 63);
+ }
+ }
+
+ public static function zigZagDecode64($uint64)
+ {
+ if (PHP_INT_SIZE == 4) {
+ if (bcmod($uint64, 2) == 0) {
+ return bcdiv($uint64, 2, 0);
+ } else {
+ return bcsub(0, bcdiv(bcadd($uint64, 1), 2, 0));
+ }
+ } else {
+ return (($uint64 >> 1) & 0x7FFFFFFFFFFFFFFF) ^ (-($uint64 & 1));
+ }
+ }
+
+ public static function readInt32(&$input, &$value)
+ {
+ return $input->readVarint32($value);
+ }
+
+ public static function readInt64(&$input, &$value)
+ {
+ return $input->readVarint64($value);
+ }
+
+ public static function readUint32(&$input, &$value)
+ {
+ return self::readInt32($input, $value);
+ }
+
+ public static function readUint64(&$input, &$value)
+ {
+ return self::readInt64($input, $value);
+ }
+
+ public static function readSint32(&$input, &$value)
+ {
+ if (!$input->readVarint32($value)) {
+ return false;
+ }
+ $value = GPBWire::zigZagDecode32($value);
+ return true;
+ }
+
+ public static function readSint64(&$input, &$value)
+ {
+ if (!$input->readVarint64($value)) {
+ return false;
+ }
+ $value = GPBWire::zigZagDecode64($value);
+ return true;
+ }
+
+ public static function readFixed32(&$input, &$value)
+ {
+ return $input->readLittleEndian32($value);
+ }
+
+ public static function readFixed64(&$input, &$value)
+ {
+ return $input->readLittleEndian64($value);
+ }
+
+ public static function readSfixed32(&$input, &$value)
+ {
+ if (!self::readFixed32($input, $value)) {
+ return false;
+ }
+ if (PHP_INT_SIZE === 8) {
+ $value |= (-($value >> 31) << 32);
+ }
+ return true;
+ }
+
+ public static function readSfixed64(&$input, &$value)
+ {
+ return $input->readLittleEndian64($value);
+ }
+
+ public static function readFloat(&$input, &$value)
+ {
+ $data = null;
+ if (!$input->readRaw(4, $data)) {
+ return false;
+ }
+ $value = unpack('f', $data)[1];
+ return true;
+ }
+
+ public static function readDouble(&$input, &$value)
+ {
+ $data = null;
+ if (!$input->readRaw(8, $data)) {
+ return false;
+ }
+ $value = unpack('d', $data)[1];
+ return true;
+ }
+
+ public static function readBool(&$input, &$value)
+ {
+ if (!$input->readVarint64($value)) {
+ return false;
+ }
+ if ($value == 0) {
+ $value = false;
+ } else {
+ $value = true;
+ }
+ return true;
+ }
+
+ public static function readString(&$input, &$value)
+ {
+ $length = 0;
+ return $input->readVarintSizeAsInt($length) && $input->readRaw($length, $value);
+ }
+
+ public static function readMessage(&$input, &$message)
+ {
+ $length = 0;
+ if (!$input->readVarintSizeAsInt($length)) {
+ return false;
+ }
+ $old_limit = 0;
+ $recursion_limit = 0;
+ $input->incrementRecursionDepthAndPushLimit(
+ $length,
+ $old_limit,
+ $recursion_limit);
+ if ($recursion_limit < 0 || !$message->parseFromStream($input)) {
+ return false;
+ }
+ return $input->decrementRecursionDepthAndPopLimit($old_limit);
+ }
+
+ public static function writeTag(&$output, $tag)
+ {
+ return $output->writeTag($tag);
+ }
+
+ public static function writeInt32(&$output, $value)
+ {
+ return $output->writeVarint32($value);
+ }
+
+ public static function writeInt64(&$output, $value)
+ {
+ return $output->writeVarint64($value);
+ }
+
+ public static function writeUint32(&$output, $value)
+ {
+ return $output->writeVarint32($value);
+ }
+
+ public static function writeUint64(&$output, $value)
+ {
+ return $output->writeVarint64($value);
+ }
+
+ public static function writeSint32(&$output, $value)
+ {
+ $value = GPBWire::zigZagEncode32($value);
+ return $output->writeVarint64($value);
+ }
+
+ public static function writeSint64(&$output, $value)
+ {
+ $value = GPBWire::zigZagEncode64($value);
+ return $output->writeVarint64($value);
+ }
+
+ public static function writeFixed32(&$output, $value)
+ {
+ return $output->writeLittleEndian32($value);
+ }
+
+ public static function writeFixed64(&$output, $value)
+ {
+ return $output->writeLittleEndian64($value);
+ }
+
+ public static function writeSfixed32(&$output, $value)
+ {
+ return $output->writeLittleEndian32($value);
+ }
+
+ public static function writeSfixed64(&$output, $value)
+ {
+ return $output->writeLittleEndian64($value);
+ }
+
+ public static function writeBool(&$output, $value)
+ {
+ if ($value) {
+ return $output->writeVarint32(1);
+ } else {
+ return $output->writeVarint32(0);
+ }
+ }
+
+ public static function writeFloat(&$output, $value)
+ {
+ $data = pack("f", $value);
+ return $output->writeRaw($data, 4);
+ }
+
+ public static function writeDouble(&$output, $value)
+ {
+ $data = pack("d", $value);
+ return $output->writeRaw($data, 8);
+ }
+
+ public static function writeString(&$output, $value)
+ {
+ return self::writeBytes($output, $value);
+ }
+
+ public static function writeBytes(&$output, $value)
+ {
+ $size = strlen($value);
+ if (!$output->writeVarint32($size)) {
+ return false;
+ }
+ return $output->writeRaw($value, $size);
+ }
+
+ public static function writeMessage(&$output, $value)
+ {
+ $size = $value->byteSize();
+ if (!$output->writeVarint32($size)) {
+ return false;
+ }
+ return $value->serializeToStream($output);
+ }
+
+ public static function makeTag($number, $type)
+ {
+ return ($number << 3) | self::getWireType($type);
+ }
+
+ public static function tagSize($field)
+ {
+ $tag = self::makeTag($field->getNumber(), $field->getType());
+ return self::varint32Size($tag);
+ }
+
+ public static function varint32Size($value)
+ {
+ if ($value < 0) {
+ return 5;
+ }
+ if ($value < (1 << 7)) {
+ return 1;
+ }
+ if ($value < (1 << 14)) {
+ return 2;
+ }
+ if ($value < (1 << 21)) {
+ return 3;
+ }
+ if ($value < (1 << 28)) {
+ return 4;
+ }
+ return 5;
+ }
+
+ public static function sint32Size($value)
+ {
+ $value = self::zigZagEncode32($value);
+ return self::varint32Size($value);
+ }
+
+ public static function sint64Size($value)
+ {
+ $value = self::zigZagEncode64($value);
+ return self::varint64Size($value);
+ }
+
+ public static function varint64Size($value)
+ {
+ if ($value < 0) {
+ return 10;
+ }
+ if ($value < (1 << 7)) {
+ return 1;
+ }
+ if ($value < (1 << 14)) {
+ return 2;
+ }
+ if ($value < (1 << 21)) {
+ return 3;
+ }
+ if ($value < (1 << 28)) {
+ return 4;
+ }
+ if ($value < (1 << 35)) {
+ return 5;
+ }
+ if ($value < (1 << 42)) {
+ return 6;
+ }
+ if ($value < (1 << 49)) {
+ return 7;
+ }
+ if ($value < (1 << 56)) {
+ return 8;
+ }
+ return 9;
+ }
+
+ public static function serializeFieldToStream(
+ $value,
+ $field,
+ $need_tag,
+ &$output)
+ {
+ if ($need_tag) {
+ if (!GPBWire::writeTag(
+ $output,
+ self::makeTag(
+ $field->getNumber(),
+ $field->getType()))) {
+ return false;
+ }
+ }
+ switch ($field->getType()) {
+ case GPBType::DOUBLE:
+ if (!GPBWire::writeDouble($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::FLOAT:
+ if (!GPBWire::writeFloat($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::INT64:
+ if (!GPBWire::writeInt64($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::UINT64:
+ if (!GPBWire::writeUint64($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::INT32:
+ if (!GPBWire::writeInt32($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::FIXED32:
+ if (!GPBWire::writeFixed32($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::FIXED64:
+ if (!GPBWire::writeFixed64($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::BOOL:
+ if (!GPBWire::writeBool($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::STRING:
+ if (!GPBWire::writeString($output, $value)) {
+ return false;
+ }
+ break;
+ // case GPBType::GROUP:
+ // echo "GROUP\xA";
+ // trigger_error("Not implemented.", E_ERROR);
+ // break;
+ case GPBType::MESSAGE:
+ if (!GPBWire::writeMessage($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::BYTES:
+ if (!GPBWire::writeBytes($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::UINT32:
+ if (!GPBWire::writeUint32($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::ENUM:
+ if (!GPBWire::writeInt32($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SFIXED32:
+ if (!GPBWire::writeSfixed32($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SFIXED64:
+ if (!GPBWire::writeSfixed64($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SINT32:
+ if (!GPBWire::writeSint32($output, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SINT64:
+ if (!GPBWire::writeSint64($output, $value)) {
+ return false;
+ }
+ break;
+ default:
+ user_error("Unsupported type.");
+ return false;
+ }
+
+ return true;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/InputStream.php b/php/src/Google/Protobuf/Internal/InputStream.php
new file mode 100644
index 00000000..6d6c74e9
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/InputStream.php
@@ -0,0 +1,373 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\Uint64;
+
+function combineInt32ToInt64($high, $low)
+{
+ $isNeg = $high < 0;
+ if ($isNeg) {
+ $high = ~$high;
+ $low = ~$low;
+ $low++;
+ if (!$low) {
+ $high++;
+ }
+ }
+ $result = bcadd(bcmul($high, 4294967296), $low);
+ if ($isNeg) {
+ $result = bcsub(0, $result);
+ }
+ return $result;
+}
+
+class InputStream
+{
+
+ private $buffer;
+ private $buffer_size_after_limit;
+ private $buffer_end;
+ private $current;
+ private $current_limit;
+ private $legitimate_message_end;
+ private $recursion_budget;
+ private $recursion_limit;
+ private $total_bytes_limit;
+ private $total_bytes_read;
+
+ const MAX_VARINT_BYTES = 10;
+ const MAX_VARINT32_BYTES = 5;
+ const DEFAULT_RECURSION_LIMIT = 100;
+ const DEFAULT_TOTAL_BYTES_LIMIT = 33554432; // 32 << 20, 32MB
+
+ public function __construct($buffer)
+ {
+ $start = 0;
+ $end = strlen($buffer);
+ $this->buffer = $buffer;
+ $this->buffer_size_after_limit = 0;
+ $this->buffer_end = $end;
+ $this->current = $start;
+ $this->current_limit = $end;
+ $this->legitimate_message_end = false;
+ $this->recursion_budget = self::DEFAULT_RECURSION_LIMIT;
+ $this->recursion_limit = self::DEFAULT_RECURSION_LIMIT;
+ $this->total_bytes_limit = self::DEFAULT_TOTAL_BYTES_LIMIT;
+ $this->total_bytes_read = $end - $start;
+ }
+
+ private function advance($amount)
+ {
+ $this->current += $amount;
+ }
+
+ private function bufferSize()
+ {
+ return $this->buffer_end - $this->current;
+ }
+
+ private function current()
+ {
+ return $this->total_bytes_read -
+ ($this->buffer_end - $this->current +
+ $this->buffer_size_after_limit);
+ }
+
+ private function recomputeBufferLimits()
+ {
+ $this->buffer_end += $this->buffer_size_after_limit;
+ $closest_limit = min($this->current_limit, $this->total_bytes_limit);
+ if ($closest_limit < $this->total_bytes_read) {
+ // The limit position is in the current buffer. We must adjust the
+ // buffer size accordingly.
+ $this->buffer_size_after_limit = $this->total_bytes_read -
+ $closest_limit;
+ $this->buffer_end -= $this->buffer_size_after_limit;
+ } else {
+ $this->buffer_size_after_limit = 0;
+ }
+ }
+
+ private function consumedEntireMessage()
+ {
+ return $this->legitimate_message_end;
+ }
+
+ /**
+ * Read uint32 into $var. Advance buffer with consumed bytes. If the
+ * contained varint is larger than 32 bits, discard the high order bits.
+ * @param $var.
+ */
+ public function readVarint32(&$var)
+ {
+ if (!$this->readVarint64($var)) {
+ return false;
+ }
+
+ if (PHP_INT_SIZE == 4) {
+ $var = bcmod($var, 4294967296);
+ } else {
+ $var &= 0xFFFFFFFF;
+ }
+
+ // Convert large uint32 to int32.
+ if ($var > 0x7FFFFFFF) {
+ if (PHP_INT_SIZE === 8) {
+ $var = $var | (0xFFFFFFFF << 32);
+ } else {
+ $var = bcsub($var, 4294967296);
+ }
+ }
+
+ $var = intval($var);
+ return true;
+ }
+
+ /**
+ * Read Uint64 into $var. Advance buffer with consumed bytes.
+ * @param $var.
+ */
+ public function readVarint64(&$var)
+ {
+ $high = 0;
+ $low = 0;
+ $count = 0;
+ $b = 0;
+
+ do {
+ if ($this->current === $this->buffer_end) {
+ return false;
+ }
+ if ($count === self::MAX_VARINT_BYTES) {
+ return false;
+ }
+ $b = ord($this->buffer[$this->current]);
+ $bits = 7 * $count;
+ if ($bits >= 32) {
+ $high |= (($b & 0x7F) << ($bits - 32));
+ } else if ($bits > 25){
+ $high_bits = $bits - 25;
+ $low = ($low | (($b & 0x7F) << $bits)) & (int) 0xFFFFFFFF;
+ $high = $b & ((0x1 << $high_bits) -1);
+ } else {
+ $low |= (($b & 0x7F) << $bits);
+ }
+
+ $this->advance(1);
+ $count += 1;
+ } while ($b & 0x80);
+
+ if (PHP_INT_SIZE == 4) {
+ $var = combineInt32ToInt64($high, $low);
+ } else {
+ $var = ($high & 0xFFFFFFFF) << 32 |
+ ($low & 0xFFFFFFFF);
+ }
+ return true;
+ }
+
+ /**
+ * Read int into $var. If the result is larger than the largest integer, $var
+ * will be -1. Advance buffer with consumed bytes.
+ * @param $var.
+ */
+ public function readVarintSizeAsInt(&$var)
+ {
+ if (!$this->readVarint64($var)) {
+ return false;
+ }
+ $var = (int)$var;
+ return true;
+ }
+
+ /**
+ * Read 32-bit unsiged integer to $var. If the buffer has less than 4 bytes,
+ * return false. Advance buffer with consumed bytes.
+ * @param $var.
+ */
+ public function readLittleEndian32(&$var)
+ {
+ $data = null;
+ if (!$this->readRaw(4, $data)) {
+ return false;
+ }
+ $var = unpack('V', $data);
+ $var = $var[1];
+ return true;
+ }
+
+ /**
+ * Read 64-bit unsiged integer to $var. If the buffer has less than 8 bytes,
+ * return false. Advance buffer with consumed bytes.
+ * @param $var.
+ */
+ public function readLittleEndian64(&$var)
+ {
+ $data = null;
+ if (!$this->readRaw(4, $data)) {
+ return false;
+ }
+ $low = unpack('V', $data)[1];
+ if (!$this->readRaw(4, $data)) {
+ return false;
+ }
+ $high = unpack('V', $data)[1];
+ if (PHP_INT_SIZE == 4) {
+ $var = combineInt32ToInt64($high, $low);
+ } else {
+ $var = ($high << 32) | $low;
+ }
+ return true;
+ }
+
+ /**
+ * Read tag into $var. Advance buffer with consumed bytes.
+ * @param $var.
+ */
+ public function readTag()
+ {
+ if ($this->current === $this->buffer_end) {
+ // Make sure that it failed due to EOF, not because we hit
+ // total_bytes_limit, which, unlike normal limits, is not a valid
+ // place to end a message.
+ $current_position = $this->total_bytes_read -
+ $this->buffer_size_after_limit;
+ if ($current_position >= $this->total_bytes_limit) {
+ // Hit total_bytes_limit_. But if we also hit the normal limit,
+ // we're still OK.
+ $this->legitimate_message_end =
+ ($this->current_limit === $this->total_bytes_limit);
+ } else {
+ $this->legitimate_message_end = true;
+ }
+ return 0;
+ }
+
+ $result = 0;
+ // The larget tag is 2^29 - 1, which can be represented by int32.
+ $success = $this->readVarint32($result);
+ if ($success) {
+ return $result;
+ } else {
+ return 0;
+ }
+ }
+
+ public function readRaw($size, &$buffer)
+ {
+ $current_buffer_size = 0;
+ if ($this->bufferSize() < $size) {
+ return false;
+ }
+
+ $buffer = substr($this->buffer, $this->current, $size);
+ $this->advance($size);
+
+ return true;
+ }
+
+ /* Places a limit on the number of bytes that the stream may read, starting
+ * from the current position. Once the stream hits this limit, it will act
+ * like the end of the input has been reached until popLimit() is called.
+ *
+ * As the names imply, the stream conceptually has a stack of limits. The
+ * shortest limit on the stack is always enforced, even if it is not the top
+ * limit.
+ *
+ * The value returned by pushLimit() is opaque to the caller, and must be
+ * passed unchanged to the corresponding call to popLimit().
+ *
+ * @param integer $byte_limit
+ */
+ public function pushLimit($byte_limit)
+ {
+ // Current position relative to the beginning of the stream.
+ $current_position = $this->current();
+ $old_limit = $this->current_limit;
+
+ // security: byte_limit is possibly evil, so check for negative values
+ // and overflow.
+ if ($byte_limit >= 0 && $byte_limit <= PHP_INT_MAX - $current_position) {
+ $this->current_limit = $current_position + $byte_limit;
+ } else {
+ // Negative or overflow.
+ $this->current_limit = PHP_INT_MAX;
+ }
+
+ // We need to enforce all limits, not just the new one, so if the previous
+ // limit was before the new requested limit, we continue to enforce the
+ // previous limit.
+ $this->current_limit = min($this->current_limit, $old_limit);
+
+ $this->recomputeBufferLimits();
+ return $old_limit;
+ }
+
+ /* The limit passed in is actually the *old* limit, which we returned from
+ * PushLimit().
+ *
+ * @param integer $byte_limit
+ */
+ public function popLimit($byte_limit)
+ {
+ $this->current_limit = $byte_limit;
+ $this->recomputeBufferLimits();
+ // We may no longer be at a legitimate message end. ReadTag() needs to
+ // be called again to find out.
+ $this->legitimate_message_end = false;
+ }
+
+ public function incrementRecursionDepthAndPushLimit(
+ $byte_limit, &$old_limit, &$recursion_budget)
+ {
+ $old_limit = $this->pushLimit($byte_limit);
+ $recursion_limit = --$this->recursion_limit;
+ }
+
+ public function decrementRecursionDepthAndPopLimit($byte_limit)
+ {
+ $result = $this->consumedEntireMessage();
+ $this->popLimit($byte_limit);
+ ++$this->recursion_budget;
+ return $result;
+ }
+
+ public function bytesUntilLimit()
+ {
+ if ($this->current_limit === PHP_INT_MAX) {
+ return -1;
+ }
+ return $this->current_limit - $this->current;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/MapEntry.php b/php/src/Google/Protobuf/Internal/MapEntry.php
new file mode 100644
index 00000000..926645e1
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/MapEntry.php
@@ -0,0 +1,57 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\Message;
+
+class MapEntry extends Message
+{
+ public $key;
+ public $value;
+
+ public function setKey(&$key) {
+ $this->key = $key;
+ }
+
+ public function getKey() {
+ return $this->key;
+ }
+
+ public function setValue(&$value) {
+ $this->value = $value;
+ }
+
+ public function getValue() {
+ return $this->value;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/MapField.php b/php/src/Google/Protobuf/Internal/MapField.php
new file mode 100644
index 00000000..14ee7ebe
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/MapField.php
@@ -0,0 +1,321 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/**
+ * MapField and MapFieldIter are used by generated protocol message classes to
+ * manipulate map fields.
+ */
+
+namespace Google\Protobuf\Internal;
+
+/**
+ * MapFieldIter is used to iterate MapField. It is also need for the foreach
+ * syntax.
+ */
+class MapFieldIter implements \Iterator
+{
+
+ /**
+ * @ignore
+ */
+ private $container;
+
+ /**
+ * Create iterator instance for MapField.
+ *
+ * @param MapField The MapField instance for which this iterator is
+ * created.
+ * @ignore
+ */
+ public function __construct($container)
+ {
+ $this->container = $container;
+ }
+
+ /**
+ * Reset the status of the iterator
+ *
+ * @return void
+ */
+ public function rewind()
+ {
+ return reset($this->container);
+ }
+
+ /**
+ * Return the element at the current position.
+ *
+ * @return object The element at the current position.
+ */
+ public function current()
+ {
+ return current($this->container);
+ }
+
+ /**
+ * Return the current key.
+ *
+ * @return object The current key.
+ */
+ public function key()
+ {
+ return key($this->container);
+ }
+
+ /**
+ * Move to the next position.
+ *
+ * @return void
+ */
+ public function next()
+ {
+ return next($this->container);
+ }
+
+ /**
+ * Check whether there are more elements to iterate.
+ *
+ * @return bool True if there are more elements to iterate.
+ */
+ public function valid()
+ {
+ return key($this->container) !== null;
+ }
+}
+
+/**
+ * @ignore
+ */
+function checkKey($key_type, &$key)
+{
+ switch ($key_type) {
+ case GPBType::INT32:
+ GPBUtil::checkInt32($key);
+ break;
+ case GPBType::UINT32:
+ GPBUtil::checkUint32($key);
+ break;
+ case GPBType::INT64:
+ GPBUtil::checkInt64($key);
+ break;
+ case GPBType::UINT64:
+ GPBUtil::checkUint64($key);
+ break;
+ case GPBType::FIXED64:
+ GPBUtil::checkUint64($key);
+ break;
+ case GPBType::FIXED32:
+ GPBUtil::checkUint32($key);
+ break;
+ case GPBType::SFIXED64:
+ GPBUtil::checkInt64($key);
+ break;
+ case GPBType::SFIXED32:
+ GPBUtil::checkInt32($key);
+ break;
+ case GPBType::SINT64:
+ GPBUtil::checkInt64($key);
+ break;
+ case GPBType::SINT32:
+ GPBUtil::checkInt32($key);
+ break;
+ case GPBType::BOOL:
+ GPBUtil::checkBool($key);
+ break;
+ case GPBType::STRING:
+ GPBUtil::checkString($key, true);
+ break;
+ default:
+ var_dump($key_type);
+ trigger_error(
+ "Given type cannot be map key.",
+ E_USER_ERROR);
+ break;
+ }
+}
+
+/**
+ * MapField is used by generated protocol message classes to manipulate map
+ * fields. It can be used like native PHP array.
+ */
+class MapField implements \ArrayAccess, \IteratorAggregate, \Countable
+{
+ /**
+ * @ignore
+ */
+ private $container;
+ /**
+ * @ignore
+ */
+ private $key_type;
+ /**
+ * @ignore
+ */
+ private $value_type;
+ /**
+ * @ignore
+ */
+ private $value_klass;
+
+ /**
+ * Constructs an instance of MapField.
+ *
+ * @param long $key_type Type of the stored key element.
+ * @param long $value_type Type of the stored value element.
+ * @param string $klass Message/Enum class name of value instance
+ * (message/enum fields only).
+ * @ignore
+ */
+ public function __construct($key_type, $value_type, $klass = null)
+ {
+ $this->container = [];
+ $this->key_type = $key_type;
+ $this->value_type = $value_type;
+ $this->klass = $klass;
+ }
+
+ /**
+ * Return the element at the given key.
+ *
+ * This will also be called for: $ele = $arr[$key]
+ *
+ * @param object $key The key of the element to be fetched.
+ * @return object The stored element at given key.
+ * @throws ErrorException Invalid type for index.
+ * @throws ErrorException Non-existing index.
+ */
+ public function offsetGet($key)
+ {
+ return $this->container[$key];
+ }
+
+ /**
+ * Assign the element at the given key.
+ *
+ * This will also be called for: $arr[$key] = $value
+ *
+ * @param object $key The key of the element to be fetched.
+ * @param object $value The element to be assigned.
+ * @return void
+ * @throws ErrorException Invalid type for key.
+ * @throws ErrorException Invalid type for value.
+ * @throws ErrorException Non-existing key.
+ */
+ public function offsetSet($key, $value)
+ {
+ checkKey($this->key_type, $key);
+
+ switch ($this->value_type) {
+ case GPBType::INT32:
+ GPBUtil::checkInt32($value);
+ break;
+ case GPBType::UINT32:
+ GPBUtil::checkUint32($value);
+ break;
+ case GPBType::INT64:
+ GPBUtil::checkInt64($value);
+ break;
+ case GPBType::UINT64:
+ GPBUtil::checkUint64($value);
+ break;
+ case GPBType::FLOAT:
+ GPBUtil::checkFloat($value);
+ break;
+ case GPBType::DOUBLE:
+ GPBUtil::checkDouble($value);
+ break;
+ case GPBType::BOOL:
+ GPBUtil::checkBool($value);
+ break;
+ case GPBType::STRING:
+ GPBUtil::checkString($value, true);
+ break;
+ case GPBType::MESSAGE:
+ GPBUtil::checkMessage($value, $this->klass);
+ break;
+ default:
+ break;
+ }
+
+ $this->container[$key] = $value;
+ }
+
+ /**
+ * Remove the element at the given key.
+ *
+ * This will also be called for: unset($arr)
+ *
+ * @param object $key The key of the element to be removed.
+ * @return void
+ * @throws ErrorException Invalid type for key.
+ */
+ public function offsetUnset($key)
+ {
+ checkKey($this->key_type, $key);
+ unset($this->container[$key]);
+ }
+
+ /**
+ * Check the existence of the element at the given key.
+ *
+ * This will also be called for: isset($arr)
+ *
+ * @param object $key The key of the element to be removed.
+ * @return bool True if the element at the given key exists.
+ * @throws ErrorException Invalid type for key.
+ */
+ public function offsetExists($key)
+ {
+ checkKey($this->key_type, $key);
+ return isset($this->container[$key]);
+ }
+
+ /**
+ * @ignore
+ */
+ public function getIterator()
+ {
+ return new MapFieldIter($this->container);
+ }
+
+ /**
+ * Return the number of stored elements.
+ *
+ * This will also be called for: count($arr)
+ *
+ * @return integer The number of stored elements.
+ */
+ public function count()
+ {
+ return count($this->container);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/Message.php b/php/src/Google/Protobuf/Internal/Message.php
new file mode 100644
index 00000000..3d1f1598
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/Message.php
@@ -0,0 +1,679 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/**
+ * Defines Message, the parent class extended by all protocol message classes.
+ */
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\InputStream;
+use Google\Protobuf\Internal\OutputStream;
+use Google\Protobuf\Internal\DescriptorPool;
+use Google\Protobuf\Internal\GPBLabel;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBWire;
+use Google\Protobuf\Internal\MapEntry;
+use Google\Protobuf\Internal\RepeatedField;
+
+/**
+ * Parent class of all proto messages. Users should not instantiate this class
+ * or extend this class or its child classes by their own. See the comment of
+ * specific functions for more details.
+ */
+class Message
+{
+
+ /**
+ * @ignore
+ */
+ private $desc;
+
+ /**
+ * @ignore
+ */
+ public function __construct($desc = NULL)
+ {
+ // MapEntry message is shared by all types of map fields, whose
+ // descriptors are different from each other. Thus, we cannot find a
+ // specific descriptor from the descriptor pool.
+ if (get_class($this) === 'Google\Protobuf\Internal\MapEntry') {
+ $this->desc = $desc;
+ return;
+ }
+ $pool = DescriptorPool::getGeneratedPool();
+ $this->desc = $pool->getDescriptorByClassName(get_class($this));
+ foreach ($this->desc->getField() as $field) {
+ $setter = $field->getSetter();
+ if ($field->isMap()) {
+ $message_type = $field->getMessageType();
+ $key_field = $message_type->getFieldByNumber(1);
+ $value_field = $message_type->getFieldByNumber(2);
+ switch ($value_field->getType()) {
+ case GPBType::MESSAGE:
+ case GPBType::GROUP:
+ $map_field = new MapField(
+ $key_field->getType(),
+ $value_field->getType(),
+ $value_field->getMessageType()->getClass());
+ $this->$setter($map_field);
+ break;
+ case GPBType::ENUM:
+ $map_field = new MapField(
+ $key_field->getType(),
+ $value_field->getType(),
+ $value_field->getEnumType()->getClass());
+ $this->$setter($map_field);
+ break;
+ default:
+ $map_field = new MapField(
+ $key_field->getType(),
+ $value_field->getType());
+ $this->$setter($map_field);
+ break;
+ }
+ } else if ($field->getLabel() === GPBLabel::REPEATED) {
+ switch ($field->getType()) {
+ case GPBType::MESSAGE:
+ case GPBType::GROUP:
+ $repeated_field = new RepeatedField(
+ $field->getType(),
+ $field->getMessageType()->getClass());
+ $this->$setter($repeated_field);
+ break;
+ case GPBType::ENUM:
+ $repeated_field = new RepeatedField(
+ $field->getType(),
+ $field->getEnumType()->getClass());
+ $this->$setter($repeated_field);
+ break;
+ default:
+ $repeated_field = new RepeatedField($field->getType());
+ $this->$setter($repeated_field);
+ break;
+ }
+ } else if ($field->getOneofIndex() !== -1) {
+ $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
+ $oneof_name = $oneof->getName();
+ $this->$oneof_name = new OneofField($oneof);
+ } else if ($field->getLabel() === GPBLabel::OPTIONAL &&
+ PHP_INT_SIZE == 4) {
+ switch ($field->getType()) {
+ case GPBType::INT64:
+ case GPBType::UINT64:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED64:
+ case GPBType::SINT64:
+ $this->$setter("0");
+ }
+ }
+ }
+ }
+
+ protected function readOneof($number)
+ {
+ $field = $this->desc->getFieldByNumber($number);
+ $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
+ $oneof_name = $oneof->getName();
+ $oneof_field = $this->$oneof_name;
+ if ($number === $oneof_field->getNumber()) {
+ return $oneof_field->getValue();
+ } else {
+ return $this->defaultValue($field);
+ }
+ }
+
+ protected function writeOneof($number, $value)
+ {
+ $field = $this->desc->getFieldByNumber($number);
+ $oneof = $this->desc->getOneofDecl()[$field->getOneofIndex()];
+ $oneof_name = $oneof->getName();
+ $oneof_field = $this->$oneof_name;
+ $oneof_field->setValue($value);
+ $oneof_field->setFieldName($field->getName());
+ $oneof_field->setNumber($number);
+ }
+
+ /**
+ * @ignore
+ */
+ private function defaultValue($field)
+ {
+ $value = null;
+
+ switch ($field->getType()) {
+ case GPBType::DOUBLE:
+ case GPBType::FLOAT:
+ return 0.0;
+ case GPBType::UINT32:
+ case GPBType::UINT64:
+ case GPBType::INT32:
+ case GPBType::INT64:
+ case GPBType::FIXED32:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED32:
+ case GPBType::SFIXED64:
+ case GPBType::SINT32:
+ case GPBType::SINT64:
+ case GPBType::ENUM:
+ return 0;
+ case GPBType::BOOL:
+ return false;
+ case GPBType::STRING:
+ case GPBType::BYTES:
+ return "";
+ case GPBType::GROUP:
+ case GPBType::MESSAGE:
+ return null;
+ default:
+ user_error("Unsupported type.");
+ return false;
+ }
+ }
+
+ /**
+ * @ignore
+ */
+ private static function parseFieldFromStreamNoTag($input, $field, &$value)
+ {
+ switch ($field->getType()) {
+ case GPBType::DOUBLE:
+ if (!GPBWire::readDouble($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::FLOAT:
+ if (!GPBWire::readFloat($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::INT64:
+ if (!GPBWire::readInt64($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::UINT64:
+ if (!GPBWire::readUint64($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::INT32:
+ if (!GPBWire::readInt32($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::FIXED64:
+ if (!GPBWire::readFixed64($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::FIXED32:
+ if (!GPBWire::readFixed32($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::BOOL:
+ if (!GPBWire::readBool($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::STRING:
+ // TODO(teboring): Add utf-8 check.
+ if (!GPBWire::readString($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::GROUP:
+ echo "GROUP\xA";
+ trigger_error("Not implemented.", E_ERROR);
+ break;
+ case GPBType::MESSAGE:
+ if ($field->isMap()) {
+ $value = new MapEntry($field->getMessageType());
+ } else {
+ $klass = $field->getMessageType()->getClass();
+ $value = new $klass;
+ }
+ if (!GPBWire::readMessage($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::BYTES:
+ if (!GPBWire::readString($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::UINT32:
+ if (!GPBWire::readUint32($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::ENUM:
+ // TODO(teboring): Check unknown enum value.
+ if (!GPBWire::readInt32($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SFIXED32:
+ if (!GPBWire::readSfixed32($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SFIXED64:
+ if (!GPBWire::readSfixed64($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SINT32:
+ if (!GPBWire::readSint32($input, $value)) {
+ return false;
+ }
+ break;
+ case GPBType::SINT64:
+ if (!GPBWire::readSint64($input, $value)) {
+ return false;
+ }
+ break;
+ default:
+ user_error("Unsupported type.");
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @ignore
+ */
+ private function parseFieldFromStream($tag, $input, $field)
+ {
+ $value = null;
+ $field_type = $field->getType();
+
+ $value_format = GPBWire::UNKNOWN;
+ if (GPBWire::getTagWireType($tag) ===
+ GPBWire::getWireType($field_type)) {
+ $value_format = GPBWire::NORMAL_FORMAT;
+ } elseif ($field->isPackable() &&
+ GPBWire::getTagWireType($tag) ===
+ GPBWire::WIRETYPE_LENGTH_DELIMITED) {
+ $value_format = GPBWire::PACKED_FORMAT;
+ }
+
+ if ($value_format === GPBWire::NORMAL_FORMAT) {
+ if (!self::parseFieldFromStreamNoTag($input, $field, $value)) {
+ return false;
+ }
+ } elseif ($value_format === GPBWire::PACKED_FORMAT) {
+ $length = 0;
+ if (!GPBWire::readInt32($input, $length)) {
+ return false;
+ }
+ $limit = $input->pushLimit($length);
+ $getter = $field->getGetter();
+ while ($input->bytesUntilLimit() > 0) {
+ if (!self::parseFieldFromStreamNoTag($input, $field, $value)) {
+ return false;
+ }
+ $this->$getter()[] = $value;
+ }
+ $input->popLimit($limit);
+ return true;
+ } else {
+ return false;
+ }
+
+ if ($field->isMap()) {
+ $getter = $field->getGetter();
+ $this->$getter()[$value->getKey()] = $value->getValue();
+ } else if ($field->isRepeated()) {
+ $getter = $field->getGetter();
+ $this->$getter()[] = $value;
+ } else {
+ $setter = $field->getSetter();
+ $this->$setter($value);
+ }
+
+ return true;
+ }
+
+ /**
+ * Parses a protocol buffer contained in a string.
+ *
+ * This function takes a string in the (non-human-readable) binary wire
+ * format, matching the encoding output by encode().
+ *
+ * @param string $data Binary protobuf data.
+ * @return bool Return true on success.
+ */
+ public function decode($data)
+ {
+ $input = new InputStream($data);
+ $this->parseFromStream($input);
+ }
+
+ /**
+ * @ignore
+ */
+ public function parseFromStream($input)
+ {
+ while (true) {
+ $tag = $input->readTag();
+ // End of input. This is a valid place to end, so return true.
+ if ($tag === 0) {
+ return true;
+ }
+
+ $number = GPBWire::getTagFieldNumber($tag);
+ $field = $this->desc->getFieldByNumber($number);
+
+ if (!$this->parseFieldFromStream($tag, $input, $field)) {
+ return false;
+ }
+ }
+ }
+
+ /**
+ * @ignore
+ */
+ private function serializeSingularFieldToStream($field, &$output)
+ {
+ if (!$this->existField($field)) {
+ return true;
+ }
+ $getter = $field->getGetter();
+ $value = $this->$getter();
+ if (!GPBWire::serializeFieldToStream($value, $field, true, $output)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * @ignore
+ */
+ private function serializeRepeatedFieldToStream($field, &$output)
+ {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count === 0) {
+ return true;
+ }
+
+ $packed = $field->getPacked();
+ if ($packed) {
+ if (!GPBWire::writeTag(
+ $output,
+ GPBWire::makeTag($field->getNumber(), GPBType::STRING))) {
+ return false;
+ }
+ $size = 0;
+ foreach ($values as $value) {
+ $size += $this->fieldDataOnlyByteSize($field, $value);
+ }
+ if (!$output->writeVarint32($size)) {
+ return false;
+ }
+ }
+
+ foreach ($values as $value) {
+ if (!GPBWire::serializeFieldToStream(
+ $value,
+ $field,
+ !$packed,
+ $output)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * @ignore
+ */
+ private function serializeMapFieldToStream($field, $output)
+ {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count === 0) {
+ return true;
+ }
+
+ foreach ($values as $key => $value) {
+ $map_entry = new MapEntry($field->getMessageType());
+ $map_entry->setKey($key);
+ $map_entry->setValue($value);
+ if (!GPBWire::serializeFieldToStream(
+ $map_entry,
+ $field,
+ true,
+ $output)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * @ignore
+ */
+ private function serializeFieldToStream(&$output, $field)
+ {
+ if ($field->isMap()) {
+ return $this->serializeMapFieldToStream($field, $output);
+ } elseif ($field->isRepeated()) {
+ return $this->serializeRepeatedFieldToStream($field, $output);
+ } else {
+ return $this->serializeSingularFieldToStream($field, $output);
+ }
+ }
+
+ /**
+ * @ignore
+ */
+ public function serializeToStream(&$output)
+ {
+ $fields = $this->desc->getField();
+ foreach ($fields as $field) {
+ if (!$this->serializeFieldToStream($output, $field)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Serialize the message to string.
+ * @return string Serialized binary protobuf data.
+ */
+ public function encode()
+ {
+ $output = new OutputStream($this->byteSize());
+ $this->serializeToStream($output);
+ return $output->getData();
+ }
+
+ /**
+ * @ignore
+ */
+ private function existField($field)
+ {
+ $getter = $field->getGetter();
+ $value = $this->$getter();
+ return $value !== $this->defaultValue($field);
+ }
+
+ /**
+ * @ignore
+ */
+ private function repeatedFieldDataOnlyByteSize($field)
+ {
+ $size = 0;
+
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count !== 0) {
+ $size += $count * GPBWire::tagSize($field);
+ foreach ($values as $value) {
+ $size += $this->singularFieldDataOnlyByteSize($field);
+ }
+ }
+ }
+
+ /**
+ * @ignore
+ */
+ private function fieldDataOnlyByteSize($field, $value)
+ {
+ $size = 0;
+
+ switch ($field->getType()) {
+ case GPBType::BOOL:
+ $size += 1;
+ break;
+ case GPBType::FLOAT:
+ case GPBType::FIXED32:
+ case GPBType::SFIXED32:
+ $size += 4;
+ break;
+ case GPBType::DOUBLE:
+ case GPBType::FIXED64:
+ case GPBType::SFIXED64:
+ $size += 8;
+ break;
+ case GPBType::UINT32:
+ case GPBType::INT32:
+ case GPBType::ENUM:
+ $size += GPBWire::varint32Size($value);
+ break;
+ case GPBType::UINT64:
+ case GPBType::INT64:
+ $size += GPBWire::varint64Size($value);
+ break;
+ case GPBType::SINT32:
+ $size += GPBWire::sint32Size($value);
+ break;
+ case GPBType::SINT64:
+ $size += GPBWire::sint64Size($value);
+ break;
+ case GPBType::STRING:
+ case GPBType::BYTES:
+ $size += strlen($value);
+ $size += GPBWire::varint32Size($size);
+ break;
+ case GPBType::MESSAGE:
+ $size += $value->byteSize();
+ $size += GPBWire::varint32Size($size);
+ break;
+ case GPBType::GROUP:
+ // TODO(teboring): Add support.
+ user_error("Unsupported type.");
+ break;
+ default:
+ user_error("Unsupported type.");
+ return 0;
+ }
+
+ return $size;
+ }
+
+ /**
+ * @ignore
+ */
+ private function fieldByteSize($field)
+ {
+ $size = 0;
+ if ($field->isMap()) {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count !== 0) {
+ $size += $count * GPBWire::tagSize($field);
+ $message_type = $field->getMessageType();
+ $key_field = $message_type->getFieldByNumber(1);
+ $value_field = $message_type->getFieldByNumber(2);
+ foreach ($values as $key => $value) {
+ $data_size = 0;
+ $data_size += $this->fieldDataOnlyByteSize($key_field, $key);
+ $data_size += $this->fieldDataOnlyByteSize(
+ $value_field,
+ $value);
+ $data_size += GPBWire::tagSize($key_field);
+ $data_size += GPBWire::tagSize($value_field);
+ $size += GPBWire::varint32Size($data_size) + $data_size;
+ }
+ }
+ } elseif ($field->isRepeated()) {
+ $getter = $field->getGetter();
+ $values = $this->$getter();
+ $count = count($values);
+ if ($count !== 0) {
+ if ($field->getPacked()) {
+ $data_size = 0;
+ foreach ($values as $value) {
+ $data_size += $this->fieldDataOnlyByteSize($field, $value);
+ }
+ $size += GPBWire::tagSize($field);
+ $size += GPBWire::varint32Size($data_size);
+ $size += $data_size;
+ } else {
+ $size += $count * GPBWire::tagSize($field);
+ foreach ($values as $value) {
+ $size += $this->fieldDataOnlyByteSize($field, $value);
+ }
+ }
+ }
+ } elseif ($this->existField($field)) {
+ $size += GPBWire::tagSize($field);
+ $getter = $field->getGetter();
+ $value = $this->$getter();
+ $size += $this->fieldDataOnlyByteSize($field, $value);
+ }
+ return $size;
+ }
+
+ /**
+ * @ignore
+ */
+ public function byteSize()
+ {
+ $size = 0;
+
+ $fields = $this->desc->getField();
+ foreach ($fields as $field) {
+ $size += $this->fieldByteSize($field);
+ }
+ return $size;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/MessageBuilderContext.php b/php/src/Google/Protobuf/Internal/MessageBuilderContext.php
new file mode 100644
index 00000000..2724d267
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/MessageBuilderContext.php
@@ -0,0 +1,120 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\GPBLabel;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\Descriptor;
+use Google\Protobuf\Internal\FieldDescriptor;
+
+class MessageBuilderContext
+{
+
+ private $descriptor;
+ private $pool;
+
+ public function __construct($full_name, $klass, $pool)
+ {
+ $this->descriptor = new Descriptor();
+ $this->descriptor->setFullName($full_name);
+ $this->descriptor->setClass($klass);
+ $this->pool = $pool;
+ }
+
+ private function getFieldDescriptor($name, $label, $type,
+ $number, $type_name = null)
+ {
+ $field = new FieldDescriptor();
+ $field->setName($name);
+ $camel_name = implode('', array_map('ucwords', explode('_', $name)));
+ $field->setGetter('get' . $camel_name);
+ $field->setSetter('set' . $camel_name);
+ $field->setType($type);
+ $field->setNumber($number);
+ $field->setLabel($label);
+
+ // At this time, the message/enum type may have not been added to pool.
+ // So we use the type name as place holder and will replace it with the
+ // actual descriptor in cross building.
+ switch ($type) {
+ case GPBType::MESSAGE:
+ $field->setMessageType($type_name);
+ break;
+ case GPBType::ENUM:
+ $field->setEnumType($type_name);
+ break;
+ default:
+ break;
+ }
+
+ return $field;
+ }
+
+ public function optional($name, $type, $number, $type_name = null)
+ {
+ $this->descriptor->addField($this->getFieldDescriptor(
+ $name,
+ GPBLabel::OPTIONAL,
+ $type,
+ $number,
+ $type_name));
+ return $this;
+ }
+
+ public function repeated($name, $type, $number, $type_name = null)
+ {
+ $this->descriptor->addField($this->getFieldDescriptor(
+ $name,
+ GPBLabel::REPEATED,
+ $type,
+ $number,
+ $type_name));
+ return $this;
+ }
+
+ public function required($name, $type, $number, $type_name = null)
+ {
+ $this->descriptor->addField($this->getFieldDescriptor(
+ $name,
+ GPBLabel::REQUIRED,
+ $type,
+ $number,
+ $type_name));
+ return $this;
+ }
+
+ public function finalizeToPool()
+ {
+ $this->pool->addDescriptor($this->descriptor);
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/OneofField.php b/php/src/Google/Protobuf/Internal/OneofField.php
new file mode 100644
index 00000000..2c689e83
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/OneofField.php
@@ -0,0 +1,77 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+class OneofField
+{
+
+ private $desc;
+ private $field_name;
+ private $number = 0;
+ private $value;
+
+ public function __construct($desc)
+ {
+ $this->desc = $desc;
+ }
+
+ public function setValue($value)
+ {
+ $this->value = $value;
+ }
+
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ public function setFieldName($field_name)
+ {
+ $this->field_name = $field_name;
+ }
+
+ public function getFieldName()
+ {
+ return $this->field_name;
+ }
+
+ public function setNumber($number)
+ {
+ $this->number = $number;
+ }
+
+ public function getNumber()
+ {
+ return $this->number;
+ }
+}
diff --git a/php/src/Google/Protobuf/Internal/OutputStream.php b/php/src/Google/Protobuf/Internal/OutputStream.php
new file mode 100644
index 00000000..587ac352
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/OutputStream.php
@@ -0,0 +1,164 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+class OutputStream
+{
+
+ private $buffer;
+ private $buffer_size;
+ private $current;
+
+ const MAX_VARINT32_BYTES = 5;
+ const MAX_VARINT64_BYTES = 10;
+
+ public function __construct($size)
+ {
+ $this->current = 0;
+ $this->buffer_size = $size;
+ $this->buffer = str_repeat(chr(0), $this->buffer_size);
+ }
+
+ public function getData()
+ {
+ return $this->buffer;
+ }
+
+ public function writeVarint32($value)
+ {
+ $bytes = str_repeat(chr(0), self::MAX_VARINT32_BYTES);
+ $size = self::writeVarintToArray($value, $bytes, true);
+ return $this->writeRaw($bytes, $size);
+ }
+
+ public function writeVarint64($value)
+ {
+ $bytes = str_repeat(chr(0), self::MAX_VARINT64_BYTES);
+ $size = self::writeVarintToArray($value, $bytes);
+ return $this->writeRaw($bytes, $size);
+ }
+
+ public function writeLittleEndian32($value)
+ {
+ $bytes = str_repeat(chr(0), 4);
+ $size = self::writeLittleEndian32ToArray($value, $bytes);
+ return $this->writeRaw($bytes, $size);
+ }
+
+ public function writeLittleEndian64($value)
+ {
+ $bytes = str_repeat(chr(0), 8);
+ $size = self::writeLittleEndian64ToArray($value, $bytes);
+ return $this->writeRaw($bytes, $size);
+ }
+
+ public function writeTag($tag)
+ {
+ return $this->writeVarint32($tag);
+ }
+
+ public function writeRaw($data, $size)
+ {
+ if ($this->buffer_size < $size) {
+ trigger_error("Output stream doesn't have enough buffer.");
+ return false;
+ }
+
+ for ($i = 0; $i < $size; $i++) {
+ $this->buffer[$this->current] = $data[$i];
+ $this->current++;
+ $this->buffer_size--;
+ }
+ return true;
+ }
+
+ private static function writeVarintToArray($value, &$buffer, $trim = false)
+ {
+ $current = 0;
+
+ $high = 0;
+ $low = 0;
+ if (PHP_INT_SIZE == 4) {
+ GPBUtil::divideInt64ToInt32($value, $high, $low, $trim);
+ } else {
+ if ($trim) {
+ $low = $value & 0xFFFFFFFF;
+ } else {
+ $low = $value;
+ }
+ }
+
+ while ($low >= 0x80 || $low < 0) {
+ $buffer[$current] = chr($low | 0x80);
+ $value = ($value >> 7) & ~(0x7F << ((PHP_INT_SIZE << 3) - 7));
+ $carry = ($high & 0x7F) << ((PHP_INT_SIZE << 3) - 7);
+ $high = ($high >> 7) & ~(0x7F << ((PHP_INT_SIZE << 3) - 7));
+ $low = (($low >> 7) & ~(0x7F << ((PHP_INT_SIZE << 3) - 7)) | $carry);
+ $current++;
+ }
+ $buffer[$current] = chr($low);
+ return $current + 1;
+ }
+
+ private static function writeLittleEndian32ToArray($value, &$buffer)
+ {
+ $buffer[0] = chr($value & 0x000000FF);
+ $buffer[1] = chr(($value >> 8) & 0x000000FF);
+ $buffer[2] = chr(($value >> 16) & 0x000000FF);
+ $buffer[3] = chr(($value >> 24) & 0x000000FF);
+ return 4;
+ }
+
+ private static function writeLittleEndian64ToArray($value, &$buffer)
+ {
+ $high = 0;
+ $low = 0;
+ if (PHP_INT_SIZE == 4) {
+ GPBUtil::divideInt64ToInt32($value, $high, $low);
+ } else {
+ $low = $value & 0xFFFFFFFF;
+ $high = ($value >> 32) & 0xFFFFFFFF;
+ }
+
+ $buffer[0] = chr($low & 0x000000FF);
+ $buffer[1] = chr(($low >> 8) & 0x000000FF);
+ $buffer[2] = chr(($low >> 16) & 0x000000FF);
+ $buffer[3] = chr(($low >> 24) & 0x000000FF);
+ $buffer[4] = chr($high & 0x000000FF);
+ $buffer[5] = chr(($high >> 8) & 0x000000FF);
+ $buffer[6] = chr(($high >> 16) & 0x000000FF);
+ $buffer[7] = chr(($high >> 24) & 0x000000FF);
+ return 8;
+ }
+
+}
diff --git a/php/src/Google/Protobuf/Internal/RepeatedField.php b/php/src/Google/Protobuf/Internal/RepeatedField.php
new file mode 100644
index 00000000..0dc5d9d2
--- /dev/null
+++ b/php/src/Google/Protobuf/Internal/RepeatedField.php
@@ -0,0 +1,303 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/**
+ * RepeatedField and RepeatedFieldIter are used by generated protocol message
+ * classes to manipulate repeated fields.
+ */
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBUtil;
+
+/**
+ * RepeatedFieldIter is used to iterate RepeatedField. It is also need for the
+ * foreach syntax.
+ */
+class RepeatedFieldIter implements \Iterator
+{
+
+ /**
+ * @ignore
+ */
+ private $position;
+ /**
+ * @ignore
+ */
+ private $container;
+
+ /**
+ * Create iterator instance for RepeatedField.
+ *
+ * @param RepeatedField The RepeatedField instance for which this iterator
+ * is created.
+ * @ignore
+ */
+ public function __construct($container)
+ {
+ $this->position = 0;
+ $this->container = $container;
+ }
+
+ /**
+ * Reset the status of the iterator
+ *
+ * @return void
+ */
+ public function rewind()
+ {
+ $this->position = 0;
+ }
+
+ /**
+ * Return the element at the current position.
+ *
+ * @return object The element at the current position.
+ */
+ public function current()
+ {
+ return $this->container[$this->position];
+ }
+
+ /**
+ * Return the current position.
+ *
+ * @return integer The current position.
+ */
+ public function key()
+ {
+ return $this->position;
+ }
+
+ /**
+ * Move to the next position.
+ *
+ * @return void
+ */
+ public function next()
+ {
+ ++$this->position;
+ }
+
+ /**
+ * Check whether there are more elements to iterate.
+ *
+ * @return bool True if there are more elements to iterate.
+ */
+ public function valid()
+ {
+ return isset($this->container[$this->position]);
+ }
+}
+
+/**
+ * RepeatedField is used by generated protocol message classes to manipulate
+ * repeated fields. It can be used like native PHP array.
+ */
+class RepeatedField implements \ArrayAccess, \IteratorAggregate, \Countable
+{
+
+ /**
+ * @ignore
+ */
+ private $container;
+ /**
+ * @ignore
+ */
+ private $type;
+ /**
+ * @ignore
+ */
+ private $klass;
+
+ /**
+ * Constructs an instance of RepeatedField.
+ *
+ * @param long $type Type of the stored element.
+ * @param string $klass Message/Enum class name (message/enum fields only).
+ * @ignore
+ */
+ public function __construct($type, $klass = null)
+ {
+ $this->container = [];
+ $this->type = $type;
+ $this->klass = $klass;
+ }
+
+ /**
+ * @ignore
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ /**
+ * @ignore
+ */
+ public function getClass()
+ {
+ return $this->klass;
+ }
+
+ /**
+ * Return the element at the given index.
+ *
+ * This will also be called for: $ele = $arr[0]
+ *
+ * @param long $offset The index of the element to be fetched.
+ * @return object The stored element at given index.
+ * @throws ErrorException Invalid type for index.
+ * @throws ErrorException Non-existing index.
+ */
+ public function offsetGet($offset)
+ {
+ return $this->container[$offset];
+ }
+
+ /**
+ * Assign the element at the given index.
+ *
+ * This will also be called for: $arr []= $ele and $arr[0] = ele
+ *
+ * @param long $offset The index of the element to be assigned.
+ * @param object $value The element to be assigned.
+ * @return void
+ * @throws ErrorException Invalid type for index.
+ * @throws ErrorException Non-existing index.
+ * @throws ErrorException Incorrect type of the element.
+ */
+ public function offsetSet($offset, $value)
+ {
+ switch ($this->type) {
+ case GPBType::INT32:
+ GPBUtil::checkInt32($value);
+ break;
+ case GPBType::UINT32:
+ GPBUtil::checkUint32($value);
+ break;
+ case GPBType::INT64:
+ GPBUtil::checkInt64($value);
+ break;
+ case GPBType::UINT64:
+ GPBUtil::checkUint64($value);
+ break;
+ case GPBType::FLOAT:
+ GPBUtil::checkFloat($value);
+ break;
+ case GPBType::DOUBLE:
+ GPBUtil::checkDouble($value);
+ break;
+ case GPBType::BOOL:
+ GPBUtil::checkBool($value);
+ break;
+ case GPBType::STRING:
+ GPBUtil::checkString($value, true);
+ break;
+ case GPBType::MESSAGE:
+ GPBUtil::checkMessage($value, $this->klass);
+ break;
+ default:
+ break;
+ }
+ if (is_null($offset)) {
+ $this->container[] = $value;
+ } else {
+ $count = count($this->container);
+ if (!is_numeric($offset) || $offset < 0 || $offset >= $count) {
+ trigger_error(
+ "Cannot modify element at the given index",
+ E_USER_ERROR);
+ return;
+ }
+ $this->container[$offset] = $value;
+ }
+ }
+
+ /**
+ * Remove the element at the given index.
+ *
+ * This will also be called for: unset($arr)
+ *
+ * @param long $offset The index of the element to be removed.
+ * @return void
+ * @throws ErrorException Invalid type for index.
+ * @throws ErrorException The element to be removed is not at the end of the
+ * RepeatedField.
+ */
+ public function offsetUnset($offset)
+ {
+ $count = count($this->container);
+ if (!is_numeric($offset) || $count === 0 || $offset !== $count - 1) {
+ trigger_error(
+ "Cannot remove element at the given index",
+ E_USER_ERROR);
+ return;
+ }
+ array_pop($this->container);
+ }
+
+ /**
+ * Check the existence of the element at the given index.
+ *
+ * This will also be called for: isset($arr)
+ *
+ * @param long $offset The index of the element to be removed.
+ * @return bool True if the element at the given offset exists.
+ * @throws ErrorException Invalid type for index.
+ */
+ public function offsetExists($offset)
+ {
+ return isset($this->container[$offset]);
+ }
+
+ /**
+ * @ignore
+ */
+ public function getIterator()
+ {
+ return new RepeatedFieldIter($this->container);
+ }
+
+ /**
+ * Return the number of stored elements.
+ *
+ * This will also be called for: count($arr)
+ *
+ * @return integer The number of stored elements.
+ */
+ public function count()
+ {
+ return count($this->container);
+ }
+}
diff --git a/php/src/Google/Protobuf/descriptor.php b/php/src/Google/Protobuf/descriptor.php
new file mode 100644
index 00000000..e5cff0ba
--- /dev/null
+++ b/php/src/Google/Protobuf/descriptor.php
@@ -0,0 +1,545 @@
+<?php
+
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\MessageOptions;
+
+class FileDescriptor
+{
+
+ private $package;
+ private $message_type = [];
+ private $enum_type = [];
+
+ public function setPackage($package)
+ {
+ $this->package = $package;
+ }
+
+ public function getPackage()
+ {
+ return $this->package;
+ }
+
+ public function getMessageType()
+ {
+ return $this->message_type;
+ }
+
+ public function addMessageType($desc)
+ {
+ $this->message_type[] = $desc;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function addEnumType($desc)
+ {
+ $this->enum_type[]= $desc;
+ }
+
+ public static function buildFromProto($proto)
+ {
+ $file = new FileDescriptor();
+ $file->setPackage($proto->getPackage());
+ foreach ($proto->getMessageType() as $message_proto) {
+ $file->addMessageType(Descriptor::buildFromProto(
+ $message_proto, $file->getPackage(), ""));
+ }
+ foreach ($proto->getEnumType() as $enum_proto) {
+ $file->getEnumType()[] =
+ $file->addEnumType(
+ EnumDescriptor::buildFromProto(
+ $enum_proto,
+ $file->getPackage(),
+ ""));
+ }
+ return $file;
+ }
+}
+
+class Descriptor
+{
+
+ private $full_name;
+ private $field = [];
+ private $nested_type = [];
+ private $enum_type = [];
+ private $klass;
+ private $options;
+ private $oneof_decl = [];
+
+ public function addOneofDecl($oneof)
+ {
+ $this->oneof_decl[] = $oneof;
+ }
+
+ public function getOneofDecl()
+ {
+ return $this->oneof_decl;
+ }
+
+ public function setFullName($full_name)
+ {
+ $this->full_name = $full_name;
+ }
+
+ public function getFullName()
+ {
+ return $this->full_name;
+ }
+
+ public function addField($field)
+ {
+ $this->field[$field->getNumber()] = $field;
+ }
+
+ public function getField()
+ {
+ return $this->field;
+ }
+
+ public function addNestedType($desc)
+ {
+ $this->nested_type[] = $desc;
+ }
+
+ public function getNestedType()
+ {
+ return $this->nested_type;
+ }
+
+ public function addEnumType($desc)
+ {
+ $this->enum_type[] = $desc;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function getFieldByNumber($number)
+ {
+ return $this->field[$number];
+ }
+
+ public function setClass($klass)
+ {
+ $this->klass = $klass;
+ }
+
+ public function getClass()
+ {
+ return $this->klass;
+ }
+
+ public function setOptions($options)
+ {
+ $this->options = $options;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public static function buildFromProto($proto, $package, $containing)
+ {
+ $desc = new Descriptor();
+
+ $message_name_without_package = "";
+ $classname = "";
+ $fullname = "";
+ getFullClassName(
+ $proto,
+ $containing,
+ $package,
+ $message_name_without_package,
+ $classname,
+ $fullname);
+ $desc->setFullName($fullname);
+ $desc->setClass($classname);
+ $desc->setOptions($proto->getOptions());
+
+ foreach ($proto->getField() as $field_proto) {
+ $desc->addField(FieldDescriptor::buildFromProto($field_proto));
+ }
+
+ // Handle nested types.
+ foreach ($proto->getNestedType() as $nested_proto) {
+ $desc->addNestedType(Descriptor::buildFromProto(
+ $nested_proto, $package, $message_name_without_package));
+ }
+
+ // Handle oneof fields.
+ foreach ($proto->getOneofDecl() as $oneof_proto) {
+ $desc->addOneofDecl(
+ OneofDescriptor::buildFromProto($oneof_proto, $desc));
+ }
+
+ return $desc;
+ }
+}
+function getFullClassName(
+ $proto,
+ $containing,
+ $package,
+ &$message_name_without_package,
+ &$classname,
+ &$fullname)
+{
+ // Full name needs to start with '.'.
+ $message_name_without_package = $proto->getName();
+ if ($containing !== "") {
+ $message_name_without_package =
+ $containing . "." . $message_name_without_package;
+ }
+ if ($package === "") {
+ $fullname = "." . $message_name_without_package;
+ } else {
+ $fullname = "." . $package . "." . $message_name_without_package;
+ }
+
+ // Nested message class names are seperated by '_', and package names are
+ // seperated by '\'.
+ $class_name_without_package =
+ implode('_', array_map('ucwords',
+ explode('.', $message_name_without_package)));
+ if ($package === "") {
+ $classname = $class_name_without_package;
+ } else {
+ $classname =
+ implode('\\', array_map('ucwords', explode('.', $package))).
+ "\\".$class_name_without_package;
+ }
+}
+
+class OneofDescriptor
+{
+
+ private $name;
+ private $fields;
+
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function addField(&$field)
+ {
+ $this->fields[] = $field;
+ }
+
+ public function getFields()
+ {
+ return $this->fields;
+ }
+
+ public static function buildFromProto($oneof_proto)
+ {
+ $oneof = new OneofDescriptor();
+ $oneof->setName($oneof_proto->getName());
+ return $oneof;
+ }
+}
+
+
+class EnumDescriptor
+{
+
+ private $klass;
+ private $full_name;
+ private $value;
+
+ public function setFullName($full_name)
+ {
+ $this->full_name = $full_name;
+ }
+
+ public function getFullName()
+ {
+ return $this->full_name;
+ }
+
+ public function addValue($number, $value)
+ {
+ $this->value[$number] = $value;
+ }
+
+ public function setClass($klass)
+ {
+ $this->klass = $klass;
+ }
+
+ public function getClass()
+ {
+ return $this->klass;
+ }
+
+ public static function buildFromProto($proto, $package, $containing)
+ {
+ $desc = new EnumDescriptor();
+
+ $enum_name_without_package = "";
+ $classname = "";
+ $fullname = "";
+ getFullClassName(
+ $proto,
+ $containing,
+ $package,
+ $enum_name_without_package,
+ $classname,
+ $fullname);
+ $desc->setFullName($fullname);
+ $desc->setClass($classname);
+
+ return $desc;
+ }
+}
+
+class EnumValueDescriptor
+{
+}
+
+class FieldDescriptor
+{
+
+ private $name;
+ private $setter;
+ private $getter;
+ private $number;
+ private $label;
+ private $type;
+ private $message_type;
+ private $enum_type;
+ private $packed;
+ private $is_map;
+ private $oneof_index = -1;
+
+ public function setOneofIndex($index)
+ {
+ $this->oneof_index = $index;
+ }
+
+ public function getOneofIndex()
+ {
+ return $this->oneof_index;
+ }
+
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setSetter($setter)
+ {
+ $this->setter = $setter;
+ }
+
+ public function getSetter()
+ {
+ return $this->setter;
+ }
+
+ public function setGetter($getter)
+ {
+ $this->getter = $getter;
+ }
+
+ public function getGetter()
+ {
+ return $this->getter;
+ }
+
+ public function setNumber($number)
+ {
+ $this->number = $number;
+ }
+
+ public function getNumber()
+ {
+ return $this->number;
+ }
+
+ public function setLabel($label)
+ {
+ $this->label = $label;
+ }
+
+ public function getLabel()
+ {
+ return $this->label;
+ }
+
+ public function isRepeated()
+ {
+ return $this->label === GPBLabel::REPEATED;
+ }
+
+ public function setType($type)
+ {
+ $this->type = $type;
+ }
+
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ public function setMessageType($message_type)
+ {
+ $this->message_type = $message_type;
+ }
+
+ public function getMessageType()
+ {
+ return $this->message_type;
+ }
+
+ public function setEnumType($enum_type)
+ {
+ $this->enum_type = $enum_type;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function setPacked($packed)
+ {
+ $this->packed = $packed;
+ }
+
+ public function getPacked()
+ {
+ return $this->packed;
+ }
+
+ public function isPackable()
+ {
+ return $this->isRepeated() && self::isTypePackable($this->type);
+ }
+
+ public function isMap()
+ {
+ return $this->getType() == GPBType::MESSAGE &&
+ !is_null($this->getMessageType()->getOptions()) &&
+ $this->getMessageType()->getOptions()->getMapEntry();
+ }
+
+ private static function isTypePackable($field_type)
+ {
+ return ($field_type !== GPBType::STRING &&
+ $field_type !== GPBType::GROUP &&
+ $field_type !== GPBType::MESSAGE &&
+ $field_type !== GPBType::BYTES);
+ }
+
+ public static function getFieldDescriptor(
+ $name,
+ $label,
+ $type,
+ $number,
+ $oneof_index,
+ $packed,
+ $type_name = null)
+ {
+ $field = new FieldDescriptor();
+ $field->setName($name);
+ $camel_name = implode('', array_map('ucwords', explode('_', $name)));
+ $field->setGetter('get' . $camel_name);
+ $field->setSetter('set' . $camel_name);
+ $field->setType($type);
+ $field->setNumber($number);
+ $field->setLabel($label);
+ $field->setPacked($packed);
+ $field->setOneofIndex($oneof_index);
+
+ // At this time, the message/enum type may have not been added to pool.
+ // So we use the type name as place holder and will replace it with the
+ // actual descriptor in cross building.
+ switch ($type) {
+ case GPBType::MESSAGE:
+ $field->setMessageType($type_name);
+ break;
+ case GPBType::ENUM:
+ $field->setEnumType($type_name);
+ break;
+ default:
+ break;
+ }
+
+ return $field;
+ }
+
+ public static function buildFromProto($proto)
+ {
+ $type_name = null;
+ switch ($proto->getType()) {
+ case GPBType::MESSAGE:
+ case GPBType::GROUP:
+ case GPBType::ENUM:
+ $type_name = $proto->getTypeName();
+ break;
+ default:
+ break;
+ }
+
+ $oneof_index = $proto->hasOneofIndex() ? $proto->getOneofIndex() : -1;
+ $packed = false;
+ $options = $proto->getOptions();
+ if ($options !== null) {
+ $packed = $options->getPacked();
+ }
+
+ return FieldDescriptor::getFieldDescriptor(
+ $proto->getName(), $proto->getLabel(), $proto->getType(),
+ $proto->getNumber(), $oneof_index, $packed, $type_name);
+ }
+}
diff --git a/php/src/Google/Protobuf/descriptor_internal.pb.php b/php/src/Google/Protobuf/descriptor_internal.pb.php
new file mode 100644
index 00000000..161a9f52
--- /dev/null
+++ b/php/src/Google/Protobuf/descriptor_internal.pb.php
@@ -0,0 +1,2532 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: google/protobuf/descriptor.proto
+
+namespace Google\Protobuf\Internal;
+
+use Google\Protobuf\Internal\DescriptorPool;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBWire;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\InputStream;
+
+use Google\Protobuf\Internal\GPBUtil;
+
+class FileDescriptorSet extends \Google\Protobuf\Internal\Message
+{
+ private $file;
+ private $has_file = false;
+
+ public function getFile()
+ {
+ return $this->file;
+ }
+
+ public function setFile(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\FileDescriptorProto::class);
+ $this->file = $var;
+ $this->has_file = true;
+ }
+
+ public function hasFile()
+ {
+ return $this->has_file;
+ }
+
+}
+
+class FileDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $package = '';
+ private $has_package = false;
+ private $dependency;
+ private $has_dependency = false;
+ private $public_dependency;
+ private $has_public_dependency = false;
+ private $weak_dependency;
+ private $has_weak_dependency = false;
+ private $message_type;
+ private $has_message_type = false;
+ private $enum_type;
+ private $has_enum_type = false;
+ private $service;
+ private $has_service = false;
+ private $extension;
+ private $has_extension = false;
+ private $options = null;
+ private $has_options = false;
+ private $source_code_info = null;
+ private $has_source_code_info = false;
+ private $syntax = '';
+ private $has_syntax = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getPackage()
+ {
+ return $this->package;
+ }
+
+ public function setPackage($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->package = $var;
+ $this->has_package = true;
+ }
+
+ public function hasPackage()
+ {
+ return $this->has_package;
+ }
+
+ public function getDependency()
+ {
+ return $this->dependency;
+ }
+
+ public function setDependency(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::STRING);
+ $this->dependency = $var;
+ $this->has_dependency = true;
+ }
+
+ public function hasDependency()
+ {
+ return $this->has_dependency;
+ }
+
+ public function getPublicDependency()
+ {
+ return $this->public_dependency;
+ }
+
+ public function setPublicDependency(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->public_dependency = $var;
+ $this->has_public_dependency = true;
+ }
+
+ public function hasPublicDependency()
+ {
+ return $this->has_public_dependency;
+ }
+
+ public function getWeakDependency()
+ {
+ return $this->weak_dependency;
+ }
+
+ public function setWeakDependency(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->weak_dependency = $var;
+ $this->has_weak_dependency = true;
+ }
+
+ public function hasWeakDependency()
+ {
+ return $this->has_weak_dependency;
+ }
+
+ public function getMessageType()
+ {
+ return $this->message_type;
+ }
+
+ public function setMessageType(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto::class);
+ $this->message_type = $var;
+ $this->has_message_type = true;
+ }
+
+ public function hasMessageType()
+ {
+ return $this->has_message_type;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function setEnumType(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto::class);
+ $this->enum_type = $var;
+ $this->has_enum_type = true;
+ }
+
+ public function hasEnumType()
+ {
+ return $this->has_enum_type;
+ }
+
+ public function getService()
+ {
+ return $this->service;
+ }
+
+ public function setService(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\ServiceDescriptorProto::class);
+ $this->service = $var;
+ $this->has_service = true;
+ }
+
+ public function hasService()
+ {
+ return $this->has_service;
+ }
+
+ public function getExtension()
+ {
+ return $this->extension;
+ }
+
+ public function setExtension(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
+ $this->extension = $var;
+ $this->has_extension = true;
+ }
+
+ public function hasExtension()
+ {
+ return $this->has_extension;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\FileOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+ public function getSourceCodeInfo()
+ {
+ return $this->source_code_info;
+ }
+
+ public function setSourceCodeInfo(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\SourceCodeInfo::class);
+ $this->source_code_info = $var;
+ $this->has_source_code_info = true;
+ }
+
+ public function hasSourceCodeInfo()
+ {
+ return $this->has_source_code_info;
+ }
+
+ public function getSyntax()
+ {
+ return $this->syntax;
+ }
+
+ public function setSyntax($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->syntax = $var;
+ $this->has_syntax = true;
+ }
+
+ public function hasSyntax()
+ {
+ return $this->has_syntax;
+ }
+
+}
+
+class DescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $field;
+ private $has_field = false;
+ private $extension;
+ private $has_extension = false;
+ private $nested_type;
+ private $has_nested_type = false;
+ private $enum_type;
+ private $has_enum_type = false;
+ private $extension_range;
+ private $has_extension_range = false;
+ private $oneof_decl;
+ private $has_oneof_decl = false;
+ private $options = null;
+ private $has_options = false;
+ private $reserved_range;
+ private $has_reserved_range = false;
+ private $reserved_name;
+ private $has_reserved_name = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getField()
+ {
+ return $this->field;
+ }
+
+ public function setField(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
+ $this->field = $var;
+ $this->has_field = true;
+ }
+
+ public function hasField()
+ {
+ return $this->has_field;
+ }
+
+ public function getExtension()
+ {
+ return $this->extension;
+ }
+
+ public function setExtension(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\FieldDescriptorProto::class);
+ $this->extension = $var;
+ $this->has_extension = true;
+ }
+
+ public function hasExtension()
+ {
+ return $this->has_extension;
+ }
+
+ public function getNestedType()
+ {
+ return $this->nested_type;
+ }
+
+ public function setNestedType(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto::class);
+ $this->nested_type = $var;
+ $this->has_nested_type = true;
+ }
+
+ public function hasNestedType()
+ {
+ return $this->has_nested_type;
+ }
+
+ public function getEnumType()
+ {
+ return $this->enum_type;
+ }
+
+ public function setEnumType(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\EnumDescriptorProto::class);
+ $this->enum_type = $var;
+ $this->has_enum_type = true;
+ }
+
+ public function hasEnumType()
+ {
+ return $this->has_enum_type;
+ }
+
+ public function getExtensionRange()
+ {
+ return $this->extension_range;
+ }
+
+ public function setExtensionRange(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ExtensionRange::class);
+ $this->extension_range = $var;
+ $this->has_extension_range = true;
+ }
+
+ public function hasExtensionRange()
+ {
+ return $this->has_extension_range;
+ }
+
+ public function getOneofDecl()
+ {
+ return $this->oneof_decl;
+ }
+
+ public function setOneofDecl(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\OneofDescriptorProto::class);
+ $this->oneof_decl = $var;
+ $this->has_oneof_decl = true;
+ }
+
+ public function hasOneofDecl()
+ {
+ return $this->has_oneof_decl;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\MessageOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+ public function getReservedRange()
+ {
+ return $this->reserved_range;
+ }
+
+ public function setReservedRange(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\DescriptorProto_ReservedRange::class);
+ $this->reserved_range = $var;
+ $this->has_reserved_range = true;
+ }
+
+ public function hasReservedRange()
+ {
+ return $this->has_reserved_range;
+ }
+
+ public function getReservedName()
+ {
+ return $this->reserved_name;
+ }
+
+ public function setReservedName(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::STRING);
+ $this->reserved_name = $var;
+ $this->has_reserved_name = true;
+ }
+
+ public function hasReservedName()
+ {
+ return $this->has_reserved_name;
+ }
+
+}
+
+class DescriptorProto_ExtensionRange extends \Google\Protobuf\Internal\Message
+{
+ private $start = 0;
+ private $has_start = false;
+ private $end = 0;
+ private $has_end = false;
+
+ public function getStart()
+ {
+ return $this->start;
+ }
+
+ public function setStart($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->start = $var;
+ $this->has_start = true;
+ }
+
+ public function hasStart()
+ {
+ return $this->has_start;
+ }
+
+ public function getEnd()
+ {
+ return $this->end;
+ }
+
+ public function setEnd($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->end = $var;
+ $this->has_end = true;
+ }
+
+ public function hasEnd()
+ {
+ return $this->has_end;
+ }
+
+}
+
+class DescriptorProto_ReservedRange extends \Google\Protobuf\Internal\Message
+{
+ private $start = 0;
+ private $has_start = false;
+ private $end = 0;
+ private $has_end = false;
+
+ public function getStart()
+ {
+ return $this->start;
+ }
+
+ public function setStart($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->start = $var;
+ $this->has_start = true;
+ }
+
+ public function hasStart()
+ {
+ return $this->has_start;
+ }
+
+ public function getEnd()
+ {
+ return $this->end;
+ }
+
+ public function setEnd($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->end = $var;
+ $this->has_end = true;
+ }
+
+ public function hasEnd()
+ {
+ return $this->has_end;
+ }
+
+}
+
+class FieldDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $number = 0;
+ private $has_number = false;
+ private $label = 0;
+ private $has_label = false;
+ private $type = 0;
+ private $has_type = false;
+ private $type_name = '';
+ private $has_type_name = false;
+ private $extendee = '';
+ private $has_extendee = false;
+ private $default_value = '';
+ private $has_default_value = false;
+ private $oneof_index = 0;
+ private $has_oneof_index = false;
+ private $json_name = '';
+ private $has_json_name = false;
+ private $options = null;
+ private $has_options = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getNumber()
+ {
+ return $this->number;
+ }
+
+ public function setNumber($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->number = $var;
+ $this->has_number = true;
+ }
+
+ public function hasNumber()
+ {
+ return $this->has_number;
+ }
+
+ public function getLabel()
+ {
+ return $this->label;
+ }
+
+ public function setLabel($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldDescriptorProto_Label::class);
+ $this->label = $var;
+ $this->has_label = true;
+ }
+
+ public function hasLabel()
+ {
+ return $this->has_label;
+ }
+
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ public function setType($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldDescriptorProto_Type::class);
+ $this->type = $var;
+ $this->has_type = true;
+ }
+
+ public function hasType()
+ {
+ return $this->has_type;
+ }
+
+ public function getTypeName()
+ {
+ return $this->type_name;
+ }
+
+ public function setTypeName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->type_name = $var;
+ $this->has_type_name = true;
+ }
+
+ public function hasTypeName()
+ {
+ return $this->has_type_name;
+ }
+
+ public function getExtendee()
+ {
+ return $this->extendee;
+ }
+
+ public function setExtendee($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->extendee = $var;
+ $this->has_extendee = true;
+ }
+
+ public function hasExtendee()
+ {
+ return $this->has_extendee;
+ }
+
+ public function getDefaultValue()
+ {
+ return $this->default_value;
+ }
+
+ public function setDefaultValue($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->default_value = $var;
+ $this->has_default_value = true;
+ }
+
+ public function hasDefaultValue()
+ {
+ return $this->has_default_value;
+ }
+
+ public function getOneofIndex()
+ {
+ return $this->oneof_index;
+ }
+
+ public function setOneofIndex($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->oneof_index = $var;
+ $this->has_oneof_index = true;
+ }
+
+ public function hasOneofIndex()
+ {
+ return $this->has_oneof_index;
+ }
+
+ public function getJsonName()
+ {
+ return $this->json_name;
+ }
+
+ public function setJsonName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->json_name = $var;
+ $this->has_json_name = true;
+ }
+
+ public function hasJsonName()
+ {
+ return $this->has_json_name;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\FieldOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+}
+
+class FieldDescriptorProto_Type
+{
+ const TYPE_DOUBLE = 1;
+ const TYPE_FLOAT = 2;
+ const TYPE_INT64 = 3;
+ const TYPE_UINT64 = 4;
+ const TYPE_INT32 = 5;
+ const TYPE_FIXED64 = 6;
+ const TYPE_FIXED32 = 7;
+ const TYPE_BOOL = 8;
+ const TYPE_STRING = 9;
+ const TYPE_GROUP = 10;
+ const TYPE_MESSAGE = 11;
+ const TYPE_BYTES = 12;
+ const TYPE_UINT32 = 13;
+ const TYPE_ENUM = 14;
+ const TYPE_SFIXED32 = 15;
+ const TYPE_SFIXED64 = 16;
+ const TYPE_SINT32 = 17;
+ const TYPE_SINT64 = 18;
+}
+
+class FieldDescriptorProto_Label
+{
+ const LABEL_OPTIONAL = 1;
+ const LABEL_REQUIRED = 2;
+ const LABEL_REPEATED = 3;
+}
+
+class OneofDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $options = null;
+ private $has_options = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\OneofOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+}
+
+class EnumDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $value;
+ private $has_value = false;
+ private $options = null;
+ private $has_options = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getValue()
+ {
+ return $this->value;
+ }
+
+ public function setValue(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\EnumValueDescriptorProto::class);
+ $this->value = $var;
+ $this->has_value = true;
+ }
+
+ public function hasValue()
+ {
+ return $this->has_value;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\EnumOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+}
+
+class EnumValueDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $number = 0;
+ private $has_number = false;
+ private $options = null;
+ private $has_options = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getNumber()
+ {
+ return $this->number;
+ }
+
+ public function setNumber($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->number = $var;
+ $this->has_number = true;
+ }
+
+ public function hasNumber()
+ {
+ return $this->has_number;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\EnumValueOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+}
+
+class ServiceDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $method;
+ private $has_method = false;
+ private $options = null;
+ private $has_options = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getMethod()
+ {
+ return $this->method;
+ }
+
+ public function setMethod(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\MethodDescriptorProto::class);
+ $this->method = $var;
+ $this->has_method = true;
+ }
+
+ public function hasMethod()
+ {
+ return $this->has_method;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\ServiceOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+}
+
+class MethodDescriptorProto extends \Google\Protobuf\Internal\Message
+{
+ private $name = '';
+ private $has_name = false;
+ private $input_type = '';
+ private $has_input_type = false;
+ private $output_type = '';
+ private $has_output_type = false;
+ private $options = null;
+ private $has_options = false;
+ private $client_streaming = false;
+ private $has_client_streaming = false;
+ private $server_streaming = false;
+ private $has_server_streaming = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getInputType()
+ {
+ return $this->input_type;
+ }
+
+ public function setInputType($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->input_type = $var;
+ $this->has_input_type = true;
+ }
+
+ public function hasInputType()
+ {
+ return $this->has_input_type;
+ }
+
+ public function getOutputType()
+ {
+ return $this->output_type;
+ }
+
+ public function setOutputType($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->output_type = $var;
+ $this->has_output_type = true;
+ }
+
+ public function hasOutputType()
+ {
+ return $this->has_output_type;
+ }
+
+ public function getOptions()
+ {
+ return $this->options;
+ }
+
+ public function setOptions(&$var)
+ {
+ GPBUtil::checkMessage($var, \Google\Protobuf\Internal\MethodOptions::class);
+ $this->options = $var;
+ $this->has_options = true;
+ }
+
+ public function hasOptions()
+ {
+ return $this->has_options;
+ }
+
+ public function getClientStreaming()
+ {
+ return $this->client_streaming;
+ }
+
+ public function setClientStreaming($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->client_streaming = $var;
+ $this->has_client_streaming = true;
+ }
+
+ public function hasClientStreaming()
+ {
+ return $this->has_client_streaming;
+ }
+
+ public function getServerStreaming()
+ {
+ return $this->server_streaming;
+ }
+
+ public function setServerStreaming($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->server_streaming = $var;
+ $this->has_server_streaming = true;
+ }
+
+ public function hasServerStreaming()
+ {
+ return $this->has_server_streaming;
+ }
+
+}
+
+class FileOptions extends \Google\Protobuf\Internal\Message
+{
+ private $java_package = '';
+ private $has_java_package = false;
+ private $java_outer_classname = '';
+ private $has_java_outer_classname = false;
+ private $java_multiple_files = false;
+ private $has_java_multiple_files = false;
+ private $java_generate_equals_and_hash = false;
+ private $has_java_generate_equals_and_hash = false;
+ private $java_string_check_utf8 = false;
+ private $has_java_string_check_utf8 = false;
+ private $optimize_for = 0;
+ private $has_optimize_for = false;
+ private $go_package = '';
+ private $has_go_package = false;
+ private $cc_generic_services = false;
+ private $has_cc_generic_services = false;
+ private $java_generic_services = false;
+ private $has_java_generic_services = false;
+ private $py_generic_services = false;
+ private $has_py_generic_services = false;
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $cc_enable_arenas = false;
+ private $has_cc_enable_arenas = false;
+ private $objc_class_prefix = '';
+ private $has_objc_class_prefix = false;
+ private $csharp_namespace = '';
+ private $has_csharp_namespace = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getJavaPackage()
+ {
+ return $this->java_package;
+ }
+
+ public function setJavaPackage($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->java_package = $var;
+ $this->has_java_package = true;
+ }
+
+ public function hasJavaPackage()
+ {
+ return $this->has_java_package;
+ }
+
+ public function getJavaOuterClassname()
+ {
+ return $this->java_outer_classname;
+ }
+
+ public function setJavaOuterClassname($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->java_outer_classname = $var;
+ $this->has_java_outer_classname = true;
+ }
+
+ public function hasJavaOuterClassname()
+ {
+ return $this->has_java_outer_classname;
+ }
+
+ public function getJavaMultipleFiles()
+ {
+ return $this->java_multiple_files;
+ }
+
+ public function setJavaMultipleFiles($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->java_multiple_files = $var;
+ $this->has_java_multiple_files = true;
+ }
+
+ public function hasJavaMultipleFiles()
+ {
+ return $this->has_java_multiple_files;
+ }
+
+ public function getJavaGenerateEqualsAndHash()
+ {
+ return $this->java_generate_equals_and_hash;
+ }
+
+ public function setJavaGenerateEqualsAndHash($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->java_generate_equals_and_hash = $var;
+ $this->has_java_generate_equals_and_hash = true;
+ }
+
+ public function hasJavaGenerateEqualsAndHash()
+ {
+ return $this->has_java_generate_equals_and_hash;
+ }
+
+ public function getJavaStringCheckUtf8()
+ {
+ return $this->java_string_check_utf8;
+ }
+
+ public function setJavaStringCheckUtf8($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->java_string_check_utf8 = $var;
+ $this->has_java_string_check_utf8 = true;
+ }
+
+ public function hasJavaStringCheckUtf8()
+ {
+ return $this->has_java_string_check_utf8;
+ }
+
+ public function getOptimizeFor()
+ {
+ return $this->optimize_for;
+ }
+
+ public function setOptimizeFor($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FileOptions_OptimizeMode::class);
+ $this->optimize_for = $var;
+ $this->has_optimize_for = true;
+ }
+
+ public function hasOptimizeFor()
+ {
+ return $this->has_optimize_for;
+ }
+
+ public function getGoPackage()
+ {
+ return $this->go_package;
+ }
+
+ public function setGoPackage($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->go_package = $var;
+ $this->has_go_package = true;
+ }
+
+ public function hasGoPackage()
+ {
+ return $this->has_go_package;
+ }
+
+ public function getCcGenericServices()
+ {
+ return $this->cc_generic_services;
+ }
+
+ public function setCcGenericServices($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->cc_generic_services = $var;
+ $this->has_cc_generic_services = true;
+ }
+
+ public function hasCcGenericServices()
+ {
+ return $this->has_cc_generic_services;
+ }
+
+ public function getJavaGenericServices()
+ {
+ return $this->java_generic_services;
+ }
+
+ public function setJavaGenericServices($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->java_generic_services = $var;
+ $this->has_java_generic_services = true;
+ }
+
+ public function hasJavaGenericServices()
+ {
+ return $this->has_java_generic_services;
+ }
+
+ public function getPyGenericServices()
+ {
+ return $this->py_generic_services;
+ }
+
+ public function setPyGenericServices($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->py_generic_services = $var;
+ $this->has_py_generic_services = true;
+ }
+
+ public function hasPyGenericServices()
+ {
+ return $this->has_py_generic_services;
+ }
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getCcEnableArenas()
+ {
+ return $this->cc_enable_arenas;
+ }
+
+ public function setCcEnableArenas($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->cc_enable_arenas = $var;
+ $this->has_cc_enable_arenas = true;
+ }
+
+ public function hasCcEnableArenas()
+ {
+ return $this->has_cc_enable_arenas;
+ }
+
+ public function getObjcClassPrefix()
+ {
+ return $this->objc_class_prefix;
+ }
+
+ public function setObjcClassPrefix($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->objc_class_prefix = $var;
+ $this->has_objc_class_prefix = true;
+ }
+
+ public function hasObjcClassPrefix()
+ {
+ return $this->has_objc_class_prefix;
+ }
+
+ public function getCsharpNamespace()
+ {
+ return $this->csharp_namespace;
+ }
+
+ public function setCsharpNamespace($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->csharp_namespace = $var;
+ $this->has_csharp_namespace = true;
+ }
+
+ public function hasCsharpNamespace()
+ {
+ return $this->has_csharp_namespace;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class FileOptions_OptimizeMode
+{
+ const SPEED = 1;
+ const CODE_SIZE = 2;
+ const LITE_RUNTIME = 3;
+}
+
+class MessageOptions extends \Google\Protobuf\Internal\Message
+{
+ private $message_set_wire_format = false;
+ private $has_message_set_wire_format = false;
+ private $no_standard_descriptor_accessor = false;
+ private $has_no_standard_descriptor_accessor = false;
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $map_entry = false;
+ private $has_map_entry = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getMessageSetWireFormat()
+ {
+ return $this->message_set_wire_format;
+ }
+
+ public function setMessageSetWireFormat($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->message_set_wire_format = $var;
+ $this->has_message_set_wire_format = true;
+ }
+
+ public function hasMessageSetWireFormat()
+ {
+ return $this->has_message_set_wire_format;
+ }
+
+ public function getNoStandardDescriptorAccessor()
+ {
+ return $this->no_standard_descriptor_accessor;
+ }
+
+ public function setNoStandardDescriptorAccessor($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->no_standard_descriptor_accessor = $var;
+ $this->has_no_standard_descriptor_accessor = true;
+ }
+
+ public function hasNoStandardDescriptorAccessor()
+ {
+ return $this->has_no_standard_descriptor_accessor;
+ }
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getMapEntry()
+ {
+ return $this->map_entry;
+ }
+
+ public function setMapEntry($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->map_entry = $var;
+ $this->has_map_entry = true;
+ }
+
+ public function hasMapEntry()
+ {
+ return $this->has_map_entry;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class FieldOptions extends \Google\Protobuf\Internal\Message
+{
+ private $ctype = 0;
+ private $has_ctype = false;
+ private $packed = false;
+ private $has_packed = false;
+ private $jstype = 0;
+ private $has_jstype = false;
+ private $lazy = false;
+ private $has_lazy = false;
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $weak = false;
+ private $has_weak = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getCtype()
+ {
+ return $this->ctype;
+ }
+
+ public function setCtype($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldOptions_CType::class);
+ $this->ctype = $var;
+ $this->has_ctype = true;
+ }
+
+ public function hasCtype()
+ {
+ return $this->has_ctype;
+ }
+
+ public function getPacked()
+ {
+ return $this->packed;
+ }
+
+ public function setPacked($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->packed = $var;
+ $this->has_packed = true;
+ }
+
+ public function hasPacked()
+ {
+ return $this->has_packed;
+ }
+
+ public function getJstype()
+ {
+ return $this->jstype;
+ }
+
+ public function setJstype($var)
+ {
+ GPBUtil::checkEnum($var, \Google\Protobuf\Internal\FieldOptions_JSType::class);
+ $this->jstype = $var;
+ $this->has_jstype = true;
+ }
+
+ public function hasJstype()
+ {
+ return $this->has_jstype;
+ }
+
+ public function getLazy()
+ {
+ return $this->lazy;
+ }
+
+ public function setLazy($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->lazy = $var;
+ $this->has_lazy = true;
+ }
+
+ public function hasLazy()
+ {
+ return $this->has_lazy;
+ }
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getWeak()
+ {
+ return $this->weak;
+ }
+
+ public function setWeak($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->weak = $var;
+ $this->has_weak = true;
+ }
+
+ public function hasWeak()
+ {
+ return $this->has_weak;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class FieldOptions_CType
+{
+ const STRING = 0;
+ const CORD = 1;
+ const STRING_PIECE = 2;
+}
+
+class FieldOptions_JSType
+{
+ const JS_NORMAL = 0;
+ const JS_STRING = 1;
+ const JS_NUMBER = 2;
+}
+
+class OneofOptions extends \Google\Protobuf\Internal\Message
+{
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class EnumOptions extends \Google\Protobuf\Internal\Message
+{
+ private $allow_alias = false;
+ private $has_allow_alias = false;
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getAllowAlias()
+ {
+ return $this->allow_alias;
+ }
+
+ public function setAllowAlias($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->allow_alias = $var;
+ $this->has_allow_alias = true;
+ }
+
+ public function hasAllowAlias()
+ {
+ return $this->has_allow_alias;
+ }
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class EnumValueOptions extends \Google\Protobuf\Internal\Message
+{
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class ServiceOptions extends \Google\Protobuf\Internal\Message
+{
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class MethodOptions extends \Google\Protobuf\Internal\Message
+{
+ private $deprecated = false;
+ private $has_deprecated = false;
+ private $uninterpreted_option;
+ private $has_uninterpreted_option = false;
+
+ public function getDeprecated()
+ {
+ return $this->deprecated;
+ }
+
+ public function setDeprecated($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->deprecated = $var;
+ $this->has_deprecated = true;
+ }
+
+ public function hasDeprecated()
+ {
+ return $this->has_deprecated;
+ }
+
+ public function getUninterpretedOption()
+ {
+ return $this->uninterpreted_option;
+ }
+
+ public function setUninterpretedOption(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption::class);
+ $this->uninterpreted_option = $var;
+ $this->has_uninterpreted_option = true;
+ }
+
+ public function hasUninterpretedOption()
+ {
+ return $this->has_uninterpreted_option;
+ }
+
+}
+
+class UninterpretedOption extends \Google\Protobuf\Internal\Message
+{
+ private $name;
+ private $has_name = false;
+ private $identifier_value = '';
+ private $has_identifier_value = false;
+ private $positive_int_value = 0;
+ private $has_positive_int_value = false;
+ private $negative_int_value = 0;
+ private $has_negative_int_value = false;
+ private $double_value = 0.0;
+ private $has_double_value = false;
+ private $string_value = '';
+ private $has_string_value = false;
+ private $aggregate_value = '';
+ private $has_aggregate_value = false;
+
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ public function setName(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\UninterpretedOption_NamePart::class);
+ $this->name = $var;
+ $this->has_name = true;
+ }
+
+ public function hasName()
+ {
+ return $this->has_name;
+ }
+
+ public function getIdentifierValue()
+ {
+ return $this->identifier_value;
+ }
+
+ public function setIdentifierValue($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->identifier_value = $var;
+ $this->has_identifier_value = true;
+ }
+
+ public function hasIdentifierValue()
+ {
+ return $this->has_identifier_value;
+ }
+
+ public function getPositiveIntValue()
+ {
+ return $this->positive_int_value;
+ }
+
+ public function setPositiveIntValue($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->positive_int_value = $var;
+ $this->has_positive_int_value = true;
+ }
+
+ public function hasPositiveIntValue()
+ {
+ return $this->has_positive_int_value;
+ }
+
+ public function getNegativeIntValue()
+ {
+ return $this->negative_int_value;
+ }
+
+ public function setNegativeIntValue($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->negative_int_value = $var;
+ $this->has_negative_int_value = true;
+ }
+
+ public function hasNegativeIntValue()
+ {
+ return $this->has_negative_int_value;
+ }
+
+ public function getDoubleValue()
+ {
+ return $this->double_value;
+ }
+
+ public function setDoubleValue($var)
+ {
+ GPBUtil::checkDouble($var);
+ $this->double_value = $var;
+ $this->has_double_value = true;
+ }
+
+ public function hasDoubleValue()
+ {
+ return $this->has_double_value;
+ }
+
+ public function getStringValue()
+ {
+ return $this->string_value;
+ }
+
+ public function setStringValue($var)
+ {
+ GPBUtil::checkString($var, False);
+ $this->string_value = $var;
+ $this->has_string_value = true;
+ }
+
+ public function hasStringValue()
+ {
+ return $this->has_string_value;
+ }
+
+ public function getAggregateValue()
+ {
+ return $this->aggregate_value;
+ }
+
+ public function setAggregateValue($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->aggregate_value = $var;
+ $this->has_aggregate_value = true;
+ }
+
+ public function hasAggregateValue()
+ {
+ return $this->has_aggregate_value;
+ }
+
+}
+
+class UninterpretedOption_NamePart extends \Google\Protobuf\Internal\Message
+{
+ private $name_part = '';
+ private $has_name_part = false;
+ private $is_extension = false;
+ private $has_is_extension = false;
+
+ public function getNamePart()
+ {
+ return $this->name_part;
+ }
+
+ public function setNamePart($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->name_part = $var;
+ $this->has_name_part = true;
+ }
+
+ public function hasNamePart()
+ {
+ return $this->has_name_part;
+ }
+
+ public function getIsExtension()
+ {
+ return $this->is_extension;
+ }
+
+ public function setIsExtension($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->is_extension = $var;
+ $this->has_is_extension = true;
+ }
+
+ public function hasIsExtension()
+ {
+ return $this->has_is_extension;
+ }
+
+}
+
+class SourceCodeInfo extends \Google\Protobuf\Internal\Message
+{
+ private $location;
+ private $has_location = false;
+
+ public function getLocation()
+ {
+ return $this->location;
+ }
+
+ public function setLocation(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\SourceCodeInfo_Location::class);
+ $this->location = $var;
+ $this->has_location = true;
+ }
+
+ public function hasLocation()
+ {
+ return $this->has_location;
+ }
+
+}
+
+class SourceCodeInfo_Location extends \Google\Protobuf\Internal\Message
+{
+ private $path;
+ private $has_path = false;
+ private $span;
+ private $has_span = false;
+ private $leading_comments = '';
+ private $has_leading_comments = false;
+ private $trailing_comments = '';
+ private $has_trailing_comments = false;
+ private $leading_detached_comments;
+ private $has_leading_detached_comments = false;
+
+ public function getPath()
+ {
+ return $this->path;
+ }
+
+ public function setPath(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->path = $var;
+ $this->has_path = true;
+ }
+
+ public function hasPath()
+ {
+ return $this->has_path;
+ }
+
+ public function getSpan()
+ {
+ return $this->span;
+ }
+
+ public function setSpan(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->span = $var;
+ $this->has_span = true;
+ }
+
+ public function hasSpan()
+ {
+ return $this->has_span;
+ }
+
+ public function getLeadingComments()
+ {
+ return $this->leading_comments;
+ }
+
+ public function setLeadingComments($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->leading_comments = $var;
+ $this->has_leading_comments = true;
+ }
+
+ public function hasLeadingComments()
+ {
+ return $this->has_leading_comments;
+ }
+
+ public function getTrailingComments()
+ {
+ return $this->trailing_comments;
+ }
+
+ public function setTrailingComments($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->trailing_comments = $var;
+ $this->has_trailing_comments = true;
+ }
+
+ public function hasTrailingComments()
+ {
+ return $this->has_trailing_comments;
+ }
+
+ public function getLeadingDetachedComments()
+ {
+ return $this->leading_detached_comments;
+ }
+
+ public function setLeadingDetachedComments(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::STRING);
+ $this->leading_detached_comments = $var;
+ $this->has_leading_detached_comments = true;
+ }
+
+ public function hasLeadingDetachedComments()
+ {
+ return $this->has_leading_detached_comments;
+ }
+
+}
+
+class GeneratedCodeInfo extends \Google\Protobuf\Internal\Message
+{
+ private $annotation;
+ private $has_annotation = false;
+
+ public function getAnnotation()
+ {
+ return $this->annotation;
+ }
+
+ public function setAnnotation(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Google\Protobuf\Internal\GeneratedCodeInfo_Annotation::class);
+ $this->annotation = $var;
+ $this->has_annotation = true;
+ }
+
+ public function hasAnnotation()
+ {
+ return $this->has_annotation;
+ }
+
+}
+
+class GeneratedCodeInfo_Annotation extends \Google\Protobuf\Internal\Message
+{
+ private $path;
+ private $has_path = false;
+ private $source_file = '';
+ private $has_source_file = false;
+ private $begin = 0;
+ private $has_begin = false;
+ private $end = 0;
+ private $has_end = false;
+
+ public function getPath()
+ {
+ return $this->path;
+ }
+
+ public function setPath(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->path = $var;
+ $this->has_path = true;
+ }
+
+ public function hasPath()
+ {
+ return $this->has_path;
+ }
+
+ public function getSourceFile()
+ {
+ return $this->source_file;
+ }
+
+ public function setSourceFile($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->source_file = $var;
+ $this->has_source_file = true;
+ }
+
+ public function hasSourceFile()
+ {
+ return $this->has_source_file;
+ }
+
+ public function getBegin()
+ {
+ return $this->begin;
+ }
+
+ public function setBegin($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->begin = $var;
+ $this->has_begin = true;
+ }
+
+ public function hasBegin()
+ {
+ return $this->has_begin;
+ }
+
+ public function getEnd()
+ {
+ return $this->end;
+ }
+
+ public function setEnd($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->end = $var;
+ $this->has_end = true;
+ }
+
+ public function hasEnd()
+ {
+ return $this->has_end;
+ }
+
+}
+
+$pool = DescriptorPool::getGeneratedPool();
+
+$pool->addMessage('google.protobuf.internal.FileDescriptorSet', FileDescriptorSet::class)
+ ->repeated('file', GPBType::MESSAGE, 1, 'google.protobuf.internal.FileDescriptorProto')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.FileDescriptorProto', FileDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->optional('package', GPBType::STRING, 2)
+ ->repeated('dependency', GPBType::STRING, 3)
+ ->repeated('public_dependency', GPBType::INT32, 10)
+ ->repeated('weak_dependency', GPBType::INT32, 11)
+ ->repeated('message_type', GPBType::MESSAGE, 4, 'google.protobuf.internal.DescriptorProto')
+ ->repeated('enum_type', GPBType::MESSAGE, 5, 'google.protobuf.internal.EnumDescriptorProto')
+ ->repeated('service', GPBType::MESSAGE, 6, 'google.protobuf.internal.ServiceDescriptorProto')
+ ->repeated('extension', GPBType::MESSAGE, 7, 'google.protobuf.internal.FieldDescriptorProto')
+ ->optional('options', GPBType::MESSAGE, 8, 'google.protobuf.internal.FileOptions')
+ ->optional('source_code_info', GPBType::MESSAGE, 9, 'google.protobuf.internal.SourceCodeInfo')
+ ->optional('syntax', GPBType::STRING, 12)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.DescriptorProto', DescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->repeated('field', GPBType::MESSAGE, 2, 'google.protobuf.internal.FieldDescriptorProto')
+ ->repeated('extension', GPBType::MESSAGE, 6, 'google.protobuf.internal.FieldDescriptorProto')
+ ->repeated('nested_type', GPBType::MESSAGE, 3, 'google.protobuf.internal.DescriptorProto')
+ ->repeated('enum_type', GPBType::MESSAGE, 4, 'google.protobuf.internal.EnumDescriptorProto')
+ ->repeated('extension_range', GPBType::MESSAGE, 5, 'google.protobuf.internal.DescriptorProto.ExtensionRange')
+ ->repeated('oneof_decl', GPBType::MESSAGE, 8, 'google.protobuf.internal.OneofDescriptorProto')
+ ->optional('options', GPBType::MESSAGE, 7, 'google.protobuf.internal.MessageOptions')
+ ->repeated('reserved_range', GPBType::MESSAGE, 9, 'google.protobuf.internal.DescriptorProto.ReservedRange')
+ ->repeated('reserved_name', GPBType::STRING, 10)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.DescriptorProto.ExtensionRange', DescriptorProto_ExtensionRange::class)
+ ->optional('start', GPBType::INT32, 1)
+ ->optional('end', GPBType::INT32, 2)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.DescriptorProto.ReservedRange', DescriptorProto_ReservedRange::class)
+ ->optional('start', GPBType::INT32, 1)
+ ->optional('end', GPBType::INT32, 2)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.FieldDescriptorProto', FieldDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->optional('number', GPBType::INT32, 3)
+ ->optional('label', GPBType::ENUM, 4, 'google.protobuf.internal.FieldDescriptorProto.Label')
+ ->optional('type', GPBType::ENUM, 5, 'google.protobuf.internal.FieldDescriptorProto.Type')
+ ->optional('type_name', GPBType::STRING, 6)
+ ->optional('extendee', GPBType::STRING, 2)
+ ->optional('default_value', GPBType::STRING, 7)
+ ->optional('oneof_index', GPBType::INT32, 9)
+ ->optional('json_name', GPBType::STRING, 10)
+ ->optional('options', GPBType::MESSAGE, 8, 'google.protobuf.internal.FieldOptions')
+ ->finalizeToPool();
+
+$pool->addEnum('google.protobuf.internal.FieldDescriptorProto.Type', Type::class)
+ ->value("TYPE_DOUBLE", 1)
+ ->value("TYPE_FLOAT", 2)
+ ->value("TYPE_INT64", 3)
+ ->value("TYPE_UINT64", 4)
+ ->value("TYPE_INT32", 5)
+ ->value("TYPE_FIXED64", 6)
+ ->value("TYPE_FIXED32", 7)
+ ->value("TYPE_BOOL", 8)
+ ->value("TYPE_STRING", 9)
+ ->value("TYPE_GROUP", 10)
+ ->value("TYPE_MESSAGE", 11)
+ ->value("TYPE_BYTES", 12)
+ ->value("TYPE_UINT32", 13)
+ ->value("TYPE_ENUM", 14)
+ ->value("TYPE_SFIXED32", 15)
+ ->value("TYPE_SFIXED64", 16)
+ ->value("TYPE_SINT32", 17)
+ ->value("TYPE_SINT64", 18)
+ ->finalizeToPool();
+
+$pool->addEnum('google.protobuf.internal.FieldDescriptorProto.Label', Label::class)
+ ->value("LABEL_OPTIONAL", 1)
+ ->value("LABEL_REQUIRED", 2)
+ ->value("LABEL_REPEATED", 3)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.OneofDescriptorProto', OneofDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->optional('options', GPBType::MESSAGE, 2, 'google.protobuf.internal.OneofOptions')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.EnumDescriptorProto', EnumDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->repeated('value', GPBType::MESSAGE, 2, 'google.protobuf.internal.EnumValueDescriptorProto')
+ ->optional('options', GPBType::MESSAGE, 3, 'google.protobuf.internal.EnumOptions')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.EnumValueDescriptorProto', EnumValueDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->optional('number', GPBType::INT32, 2)
+ ->optional('options', GPBType::MESSAGE, 3, 'google.protobuf.internal.EnumValueOptions')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.ServiceDescriptorProto', ServiceDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->repeated('method', GPBType::MESSAGE, 2, 'google.protobuf.internal.MethodDescriptorProto')
+ ->optional('options', GPBType::MESSAGE, 3, 'google.protobuf.internal.ServiceOptions')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.MethodDescriptorProto', MethodDescriptorProto::class)
+ ->optional('name', GPBType::STRING, 1)
+ ->optional('input_type', GPBType::STRING, 2)
+ ->optional('output_type', GPBType::STRING, 3)
+ ->optional('options', GPBType::MESSAGE, 4, 'google.protobuf.internal.MethodOptions')
+ ->optional('client_streaming', GPBType::BOOL, 5)
+ ->optional('server_streaming', GPBType::BOOL, 6)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.FileOptions', FileOptions::class)
+ ->optional('java_package', GPBType::STRING, 1)
+ ->optional('java_outer_classname', GPBType::STRING, 8)
+ ->optional('java_multiple_files', GPBType::BOOL, 10)
+ ->optional('java_generate_equals_and_hash', GPBType::BOOL, 20)
+ ->optional('java_string_check_utf8', GPBType::BOOL, 27)
+ ->optional('optimize_for', GPBType::ENUM, 9, 'google.protobuf.internal.FileOptions.OptimizeMode')
+ ->optional('go_package', GPBType::STRING, 11)
+ ->optional('cc_generic_services', GPBType::BOOL, 16)
+ ->optional('java_generic_services', GPBType::BOOL, 17)
+ ->optional('py_generic_services', GPBType::BOOL, 18)
+ ->optional('deprecated', GPBType::BOOL, 23)
+ ->optional('cc_enable_arenas', GPBType::BOOL, 31)
+ ->optional('objc_class_prefix', GPBType::STRING, 36)
+ ->optional('csharp_namespace', GPBType::STRING, 37)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addEnum('google.protobuf.internal.FileOptions.OptimizeMode', OptimizeMode::class)
+ ->value("SPEED", 1)
+ ->value("CODE_SIZE", 2)
+ ->value("LITE_RUNTIME", 3)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.MessageOptions', MessageOptions::class)
+ ->optional('message_set_wire_format', GPBType::BOOL, 1)
+ ->optional('no_standard_descriptor_accessor', GPBType::BOOL, 2)
+ ->optional('deprecated', GPBType::BOOL, 3)
+ ->optional('map_entry', GPBType::BOOL, 7)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.FieldOptions', FieldOptions::class)
+ ->optional('ctype', GPBType::ENUM, 1, 'google.protobuf.internal.FieldOptions.CType')
+ ->optional('packed', GPBType::BOOL, 2)
+ ->optional('jstype', GPBType::ENUM, 6, 'google.protobuf.internal.FieldOptions.JSType')
+ ->optional('lazy', GPBType::BOOL, 5)
+ ->optional('deprecated', GPBType::BOOL, 3)
+ ->optional('weak', GPBType::BOOL, 10)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addEnum('google.protobuf.internal.FieldOptions.CType', CType::class)
+ ->value("STRING", 0)
+ ->value("CORD", 1)
+ ->value("STRING_PIECE", 2)
+ ->finalizeToPool();
+
+$pool->addEnum('google.protobuf.internal.FieldOptions.JSType', JSType::class)
+ ->value("JS_NORMAL", 0)
+ ->value("JS_STRING", 1)
+ ->value("JS_NUMBER", 2)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.OneofOptions', OneofOptions::class)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.EnumOptions', EnumOptions::class)
+ ->optional('allow_alias', GPBType::BOOL, 2)
+ ->optional('deprecated', GPBType::BOOL, 3)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.EnumValueOptions', EnumValueOptions::class)
+ ->optional('deprecated', GPBType::BOOL, 1)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.ServiceOptions', ServiceOptions::class)
+ ->optional('deprecated', GPBType::BOOL, 33)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.MethodOptions', MethodOptions::class)
+ ->optional('deprecated', GPBType::BOOL, 33)
+ ->repeated('uninterpreted_option', GPBType::MESSAGE, 999, 'google.protobuf.internal.UninterpretedOption')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.UninterpretedOption', UninterpretedOption::class)
+ ->repeated('name', GPBType::MESSAGE, 2, 'google.protobuf.internal.UninterpretedOption.NamePart')
+ ->optional('identifier_value', GPBType::STRING, 3)
+ ->optional('positive_int_value', GPBType::UINT64, 4)
+ ->optional('negative_int_value', GPBType::INT64, 5)
+ ->optional('double_value', GPBType::DOUBLE, 6)
+ ->optional('string_value', GPBType::BYTES, 7)
+ ->optional('aggregate_value', GPBType::STRING, 8)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.UninterpretedOption.NamePart', UninterpretedOption_NamePart::class)
+ ->required('name_part', GPBType::STRING, 1)
+ ->required('is_extension', GPBType::BOOL, 2)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.SourceCodeInfo', SourceCodeInfo::class)
+ ->repeated('location', GPBType::MESSAGE, 1, 'google.protobuf.internal.SourceCodeInfo.Location')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.SourceCodeInfo.Location', SourceCodeInfo_Location::class)
+ ->repeated('path', GPBType::INT32, 1)
+ ->repeated('span', GPBType::INT32, 2)
+ ->optional('leading_comments', GPBType::STRING, 3)
+ ->optional('trailing_comments', GPBType::STRING, 4)
+ ->repeated('leading_detached_comments', GPBType::STRING, 6)
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.GeneratedCodeInfo', GeneratedCodeInfo::class)
+ ->repeated('annotation', GPBType::MESSAGE, 1, 'google.protobuf.internal.GeneratedCodeInfo.Annotation')
+ ->finalizeToPool();
+
+$pool->addMessage('google.protobuf.internal.GeneratedCodeInfo.Annotation', GeneratedCodeInfo_Annotation::class)
+ ->repeated('path', GPBType::INT32, 1)
+ ->optional('source_file', GPBType::STRING, 2)
+ ->optional('begin', GPBType::INT32, 3)
+ ->optional('end', GPBType::INT32, 4)
+ ->finalizeToPool();
+
+$pool->finish();
diff --git a/php/src/phpdoc.dist.xml b/php/src/phpdoc.dist.xml
new file mode 100644
index 00000000..dd313025
--- /dev/null
+++ b/php/src/phpdoc.dist.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!-- Install phpDocumentor to generate docs. -->
+<phpdoc>
+ <parser>
+ <target>doc</target>
+ </parser>
+ <transformer>
+ <target>doc</target>
+ </transformer>
+ <files>
+ <file>Google/Protobuf/Internal/MapField.php</file>
+ <file>Google/Protobuf/Internal/Message.php</file>
+ <file>Google/Protobuf/Internal/RepeatedField.php</file>
+ </files>
+</phpdoc>
diff --git a/php/tests/array_test.php b/php/tests/array_test.php
new file mode 100644
index 00000000..a79a08bc
--- /dev/null
+++ b/php/tests/array_test.php
@@ -0,0 +1,940 @@
+<?php
+
+require_once('test.pb.php');
+require_once('test_util.php');
+
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBType;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+
+class RepeatedFieldTest extends PHPUnit_Framework_TestCase
+{
+
+ #########################################################
+ # Test int32 field.
+ #########################################################
+
+ public function testInt32()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+
+ // Test append.
+ $arr []= MAX_INT32;
+ $this->assertSame(MAX_INT32, $arr[0]);
+ $arr []= MIN_INT32;
+ $this->assertSame(MIN_INT32, $arr[1]);
+
+ $arr []= 1.1;
+ $this->assertSame(1, $arr[2]);
+ $arr []= MAX_INT32_FLOAT;
+ $this->assertSame(MAX_INT32, $arr[3]);
+ $arr []= MAX_INT32_FLOAT;
+ $this->assertSame(MAX_INT32, $arr[4]);
+
+ $arr []= '2';
+ $this->assertSame(2, $arr[5]);
+ $arr []= '3.1';
+ $this->assertSame(3, $arr[6]);
+ $arr []= MAX_INT32_STRING;
+ $this->assertSame(MAX_INT32, $arr[7]);
+
+ $this->assertEquals(8, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ $this->assertSame(0, $arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= MAX_INT32;
+ $this->assertSame(MAX_INT32, $arr[0]);
+ $arr [1]= MIN_INT32;
+ $this->assertSame(MIN_INT32, $arr[1]);
+
+ $arr [2]= 1.1;
+ $this->assertSame(1, $arr[2]);
+ $arr [3]= MAX_INT32_FLOAT;
+ $this->assertSame(MAX_INT32, $arr[3]);
+ $arr [4]= MAX_INT32_FLOAT;
+ $this->assertSame(MAX_INT32, $arr[4]);
+
+ $arr [5]= '2';
+ $this->assertSame(2, $arr[5]);
+ $arr [6]= '3.1';
+ $this->assertSame(3, $arr[6]);
+ $arr [7]= MAX_INT32_STRING;
+ $this->assertSame(MAX_INT32, $arr[7]);
+
+ // Test foreach.
+ $arr = new RepeatedField(GPBType::INT32);
+ for ($i = 0; $i < 3; $i++) {
+ $arr []= $i;
+ }
+ $i = 0;
+ foreach ($arr as $val) {
+ $this->assertSame($i++, $val);
+ }
+ $this->assertSame(3, $i);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= 0;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= 0;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test uint32 field.
+ #########################################################
+
+ public function testUint32()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+
+ // Test append.
+ $arr []= MAX_UINT32;
+ $this->assertSame(-1, $arr[0]);
+ $arr []= -1;
+ $this->assertSame(-1, $arr[1]);
+ $arr []= MIN_UINT32;
+ $this->assertSame(MIN_UINT32, $arr[2]);
+
+ $arr []= 1.1;
+ $this->assertSame(1, $arr[3]);
+ $arr []= MAX_UINT32_FLOAT;
+ $this->assertSame(-1, $arr[4]);
+ $arr []= -1.0;
+ $this->assertSame(-1, $arr[5]);
+ $arr []= MIN_UINT32_FLOAT;
+ $this->assertSame(MIN_UINT32, $arr[6]);
+
+ $arr []= '2';
+ $this->assertSame(2, $arr[7]);
+ $arr []= '3.1';
+ $this->assertSame(3, $arr[8]);
+ $arr []= MAX_UINT32_STRING;
+ $this->assertSame(-1, $arr[9]);
+ $arr []= '-1.0';
+ $this->assertSame(-1, $arr[10]);
+ $arr []= MIN_UINT32_STRING;
+ $this->assertSame(MIN_UINT32, $arr[11]);
+
+ $this->assertEquals(12, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ $this->assertSame(0, $arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= MAX_UINT32;
+ $this->assertSame(-1, $arr[0]);
+ $arr [1]= -1;
+ $this->assertSame(-1, $arr[1]);
+ $arr [2]= MIN_UINT32;
+ $this->assertSame(MIN_UINT32, $arr[2]);
+
+ $arr [3]= 1.1;
+ $this->assertSame(1, $arr[3]);
+ $arr [4]= MAX_UINT32_FLOAT;
+ $this->assertSame(-1, $arr[4]);
+ $arr [5]= -1.0;
+ $this->assertSame(-1, $arr[5]);
+ $arr [6]= MIN_UINT32_FLOAT;
+ $this->assertSame(MIN_UINT32, $arr[6]);
+
+ $arr [7]= '2';
+ $this->assertSame(2, $arr[7]);
+ $arr [8]= '3.1';
+ $this->assertSame(3, $arr[8]);
+ $arr [9]= MAX_UINT32_STRING;
+ $this->assertSame(-1, $arr[9]);
+ $arr [10]= '-1.0';
+ $this->assertSame(-1, $arr[10]);
+ $arr [11]= MIN_UINT32_STRING;
+ $this->assertSame(MIN_UINT32, $arr[11]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr []= 0;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT32);
+ $arr []= 0;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test int64 field.
+ #########################################################
+
+ public function testInt64()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+
+ // Test append.
+ $arr []= MAX_INT64;
+ $arr []= MIN_INT64;
+ $arr []= 1.1;
+ $arr []= '2';
+ $arr []= '3.1';
+ $arr []= MAX_INT64_STRING;
+ $arr []= MIN_INT64_STRING;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_INT64, $arr[0]);
+ $this->assertSame(MIN_INT64, $arr[1]);
+ $this->assertSame('1', $arr[2]);
+ $this->assertSame('2', $arr[3]);
+ $this->assertSame('3', $arr[4]);
+ $this->assertSame(MAX_INT64_STRING, $arr[5]);
+ $this->assertSame(MIN_INT64_STRING, $arr[6]);
+ } else {
+ $this->assertSame(MAX_INT64, $arr[0]);
+ $this->assertSame(MIN_INT64, $arr[1]);
+ $this->assertSame(1, $arr[2]);
+ $this->assertSame(2, $arr[3]);
+ $this->assertSame(3, $arr[4]);
+ $this->assertSame(MAX_INT64, $arr[5]);
+ $this->assertSame(MIN_INT64, $arr[6]);
+ }
+
+
+ $this->assertEquals(7, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('0', $arr[$i]);
+ } else {
+ $this->assertSame(0, $arr[$i]);
+ }
+ }
+
+ // Test set.
+ $arr [0]= MAX_INT64;
+ $arr [1]= MIN_INT64;
+ $arr [2]= 1.1;
+ $arr [3]= '2';
+ $arr [4]= '3.1';
+ $arr [5]= MAX_INT64_STRING;
+ $arr [6]= MIN_INT64_STRING;
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_INT64_STRING, $arr[0]);
+ $this->assertSame(MIN_INT64_STRING, $arr[1]);
+ $this->assertSame('1', $arr[2]);
+ $this->assertSame('2', $arr[3]);
+ $this->assertSame('3', $arr[4]);
+ $this->assertSame(MAX_INT64_STRING, $arr[5]);
+ $this->assertEquals(MIN_INT64_STRING, $arr[6]);
+ } else {
+ $this->assertSame(MAX_INT64, $arr[0]);
+ $this->assertSame(MIN_INT64, $arr[1]);
+ $this->assertSame(1, $arr[2]);
+ $this->assertSame(2, $arr[3]);
+ $this->assertSame(3, $arr[4]);
+ $this->assertSame(MAX_INT64, $arr[5]);
+ $this->assertEquals(MIN_INT64, $arr[6]);
+ }
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr []= 0;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::INT64);
+ $arr []= 0;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test uint64 field.
+ #########################################################
+
+ public function testUint64()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+
+ // Test append.
+ $arr []= MAX_UINT64;
+ $arr []= 1.1;
+ $arr []= '2';
+ $arr []= '3.1';
+ $arr []= MAX_UINT64_STRING;
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_UINT64_STRING, $arr[0]);
+ $this->assertSame('1', $arr[1]);
+ $this->assertSame('2', $arr[2]);
+ $this->assertSame('3', $arr[3]);
+ $this->assertSame(MAX_UINT64_STRING, $arr[4]);
+ } else {
+ $this->assertSame(MAX_UINT64, $arr[0]);
+ $this->assertSame(1, $arr[1]);
+ $this->assertSame(2, $arr[2]);
+ $this->assertSame(3, $arr[3]);
+ $this->assertSame(MAX_UINT64, $arr[4]);
+ $this->assertSame(5, count($arr));
+ }
+
+ $this->assertSame(5, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('0', $arr[$i]);
+ } else {
+ $this->assertSame(0, $arr[$i]);
+ }
+ }
+
+ // Test set.
+ $arr [0]= MAX_UINT64;
+ $arr [1]= 1.1;
+ $arr [2]= '2';
+ $arr [3]= '3.1';
+ $arr [4]= MAX_UINT64_STRING;
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_UINT64_STRING, $arr[0]);
+ $this->assertSame('1', $arr[1]);
+ $this->assertSame('2', $arr[2]);
+ $this->assertSame('3', $arr[3]);
+ $this->assertSame(MAX_UINT64_STRING, $arr[4]);
+ } else {
+ $this->assertSame(MAX_UINT64, $arr[0]);
+ $this->assertSame(1, $arr[1]);
+ $this->assertSame(2, $arr[2]);
+ $this->assertSame(3, $arr[3]);
+ $this->assertSame(MAX_UINT64, $arr[4]);
+ }
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64AppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr []= 0;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64AppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::UINT64);
+ $arr []= 0;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test float field.
+ #########################################################
+
+ public function testFloat()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+
+ // Test append.
+ $arr []= 1;
+ $this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
+
+ $arr []= 1.1;
+ $this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
+
+ $arr []= '2';
+ $this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
+ $arr []= '3.1';
+ $this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
+
+ $this->assertEquals(4, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ $this->assertSame(0.0, $arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= 1;
+ $this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
+
+ $arr [1]= 1.1;
+ $this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
+
+ $arr [2]= '2';
+ $this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
+ $arr [3]= '3.1';
+ $this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatAppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatSetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr []= 0.0;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::FLOAT);
+ $arr []= 0.0;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test double field.
+ #########################################################
+
+ public function testDouble()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+
+ // Test append.
+ $arr []= 1;
+ $this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
+
+ $arr []= 1.1;
+ $this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
+
+ $arr []= '2';
+ $this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
+ $arr []= '3.1';
+ $this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
+
+ $this->assertEquals(4, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ $this->assertSame(0.0, $arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= 1;
+ $this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
+
+ $arr [1]= 1.1;
+ $this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
+
+ $arr [2]= '2';
+ $this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
+ $arr [3]= '3.1';
+ $this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleAppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr []= 0.0;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::DOUBLE);
+ $arr []= 0.0;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test bool field.
+ #########################################################
+
+ public function testBool()
+ {
+ $arr = new RepeatedField(GPBType::BOOL);
+
+ // Test append.
+ $arr []= true;
+ $this->assertSame(true, $arr[0]);
+
+ $arr []= -1;
+ $this->assertSame(true, $arr[1]);
+
+ $arr []= 1.1;
+ $this->assertSame(true, $arr[2]);
+
+ $arr []= '';
+ $this->assertSame(false, $arr[3]);
+
+ $this->assertEquals(4, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = 0;
+ $this->assertSame(false, $arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= true;
+ $this->assertSame(true, $arr[0]);
+
+ $arr [1]= -1;
+ $this->assertSame(true, $arr[1]);
+
+ $arr [2]= 1.1;
+ $this->assertSame(true, $arr[2]);
+
+ $arr [3]= '';
+ $this->assertSame(false, $arr[3]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::BOOL);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::BOOL);
+ $arr []= true;
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test string field.
+ #########################################################
+
+ public function testString()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+
+ // Test append.
+ $arr []= 'abc';
+ $this->assertSame('abc', $arr[0]);
+
+ $arr []= 1;
+ $this->assertSame('1', $arr[1]);
+
+ $arr []= 1.1;
+ $this->assertSame('1.1', $arr[2]);
+
+ $arr []= true;
+ $this->assertSame('1', $arr[3]);
+
+ $this->assertEquals(4, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = '';
+ $this->assertSame('', $arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= 'abc';
+ $this->assertSame('abc', $arr[0]);
+
+ $arr [1]= 1;
+ $this->assertSame('1', $arr[1]);
+
+ $arr [2]= 1.1;
+ $this->assertSame('1.1', $arr[2]);
+
+ $arr [3]= true;
+ $this->assertSame('1', $arr[3]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringAppendMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $arr []= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $arr []= 'abc';
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringAppendInvalidUTF8Fail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $hex = hex2bin("ff");
+ $arr []= $hex;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetInvalidUTF8Fail()
+ {
+ $arr = new RepeatedField(GPBType::STRING);
+ $arr []= 'abc';
+ $hex = hex2bin("ff");
+ $arr [0]= $hex;
+ }
+
+ #########################################################
+ # Test message field.
+ #########################################################
+
+ public function testMessage()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+
+ // Test append.
+ $sub_m = new TestMessage_Sub();
+ $sub_m->setA(1);
+ $arr []= $sub_m;
+ $this->assertSame(1, $arr[0]->getA());
+
+ $null = null;
+ $arr []= $null;
+ $this->assertNull($arr[1]);
+
+ $this->assertEquals(2, count($arr));
+
+ for ($i = 0; $i < count($arr); $i++) {
+ $arr[$i] = $null;
+ $this->assertNull($arr[$i]);
+ }
+
+ // Test set.
+ $arr [0]= $sub_m;
+ $this->assertSame(1, $arr[0]->getA());
+
+ $arr [1]= $null;
+ $this->assertNull($arr[1]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendIntFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr []= 1;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetIntFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr []= new TestMessage_Sub;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendStringFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr []= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetStringFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr []= new TestMessage_Sub;
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageAppendOtherMessageFail()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage_Sub::class);
+ $arr []= new TestMessage;
+ }
+
+ #########################################################
+ # Test offset type
+ #########################################################
+
+ public function testOffset()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= 0;
+
+ $arr [0]= 1;
+ $this->assertSame(1, $arr[0]);
+ $this->assertSame(1, count($arr));
+
+ $arr ['0']= 2;
+ $this->assertSame(2, $arr['0']);
+ $this->assertSame(2, $arr[0]);
+ $this->assertSame(1, count($arr));
+
+ $arr [0.0]= 3;
+ $this->assertSame(3, $arr[0.0]);
+ $this->assertSame(1, count($arr));
+ }
+
+ public function testInsertRemoval()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+
+ $arr []= 0;
+ $arr []= 1;
+ $arr []= 2;
+ $this->assertSame(3, count($arr));
+
+ unset($arr[2]);
+ $this->assertSame(2, count($arr));
+ $this->assertSame(0, $arr[0]);
+ $this->assertSame(1, $arr[1]);
+
+ $arr [] = 3;
+ $this->assertSame(3, count($arr));
+ $this->assertSame(0, $arr[0]);
+ $this->assertSame(1, $arr[1]);
+ $this->assertSame(3, $arr[2]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRemoveMiddleFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+
+ $arr []= 0;
+ $arr []= 1;
+ $arr []= 2;
+ $this->assertSame(3, count($arr));
+
+ unset($arr[1]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRemoveEmptyFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+
+ unset($arr[0]);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageOffsetFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= 0;
+ $arr [new TestMessage_Sub()]= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringOffsetFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr []= 0;
+ $arr ['abc']= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testSetNonExistedOffsetFail()
+ {
+ $arr = new RepeatedField(GPBType::INT32);
+ $arr [0]= 0;
+ }
+
+ #########################################################
+ # Test memory leak
+ #########################################################
+
+ public function testCycleLeak()
+ {
+ $arr = new RepeatedField(GPBType::MESSAGE, TestMessage::class);
+ $arr []= new TestMessage;
+ $arr[0]->SetRepeatedRecursive($arr);
+
+ // Clean up memory before test.
+ gc_collect_cycles();
+ $start = memory_get_usage();
+ unset($arr);
+
+ // Explicitly trigger garbage collection.
+ gc_collect_cycles();
+
+ $end = memory_get_usage();
+ $this->assertLessThan($start, $end);
+ }
+}
diff --git a/php/tests/autoload.php b/php/tests/autoload.php
deleted file mode 100644
index af88ba01..00000000
--- a/php/tests/autoload.php
+++ /dev/null
@@ -1,4 +0,0 @@
-<?php
-
-require_once('test.pb.php');
-require_once('test_util.php');
diff --git a/php/tests/encode_decode_test.php b/php/tests/encode_decode_test.php
new file mode 100644
index 00000000..d07907c0
--- /dev/null
+++ b/php/tests/encode_decode_test.php
@@ -0,0 +1,136 @@
+<?php
+
+require_once('test.pb.php');
+require_once('test_base.php');
+require_once('test_util.php');
+
+use Google\Protobuf\RepeatedField;
+use Google\Protobuf\GPBType;
+use Foo\TestEnum;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+use Foo\TestPackedMessage;
+use Foo\TestUnpackedMessage;
+
+class EncodeDecodeTest extends TestBase
+{
+
+ public function testEncode()
+ {
+ $from = new TestMessage();
+ $this->expectEmptyFields($from);
+ $this->setFields($from);
+ $this->expectFields($from);
+
+ $data = $from->encode();
+ $this->assertSame(TestUtil::getGoldenTestMessage(), $data);
+ }
+
+ public function testDecode()
+ {
+ $to = new TestMessage();
+ $to->decode(TestUtil::getGoldenTestMessage());
+ $this->expectFields($to);
+ }
+
+ public function testEncodeDecode()
+ {
+ $from = new TestMessage();
+ $this->expectEmptyFields($from);
+ $this->setFields($from);
+ $this->expectFields($from);
+
+ $data = $from->encode();
+
+ $to = new TestMessage();
+ $to->decode($data);
+ $this->expectFields($to);
+ }
+
+ public function testEncodeDecodeEmpty()
+ {
+ $from = new TestMessage();
+ $this->expectEmptyFields($from);
+
+ $data = $from->encode();
+
+ $to = new TestMessage();
+ $to->decode($data);
+ $this->expectEmptyFields($to);
+ }
+
+ public function testEncodeDecodeOneof()
+ {
+ $m = new TestMessage();
+
+ $m->setOneofInt32(1);
+ $data = $m->encode();
+ $n = new TestMessage();
+ $n->decode($data);
+ $this->assertSame(1, $n->getOneofInt32());
+
+ $m->setOneofFloat(2.0);
+ $data = $m->encode();
+ $n = new TestMessage();
+ $n->decode($data);
+ $this->assertSame(2.0, $n->getOneofFloat());
+
+ $m->setOneofString('abc');
+ $data = $m->encode();
+ $n = new TestMessage();
+ $n->decode($data);
+ $this->assertSame('abc', $n->getOneofString());
+
+ $sub_m = new TestMessage_Sub();
+ $sub_m->setA(1);
+ $m->setOneofMessage($sub_m);
+ $data = $m->encode();
+ $n = new TestMessage();
+ $n->decode($data);
+ $this->assertSame(1, $n->getOneofMessage()->getA());
+ }
+
+ public function testPackedEncode()
+ {
+ $from = new TestPackedMessage();
+ TestUtil::setTestPackedMessage($from);
+ $this->assertSame(TestUtil::getGoldenTestPackedMessage(),
+ $from->encode());
+ }
+
+ public function testPackedDecodePacked()
+ {
+ $to = new TestPackedMessage();
+ $to->decode(TestUtil::getGoldenTestPackedMessage());
+ TestUtil::assertTestPackedMessage($to);
+ }
+
+ public function testPackedDecodeUnpacked()
+ {
+ $to = new TestPackedMessage();
+ $to->decode(TestUtil::getGoldenTestUnpackedMessage());
+ TestUtil::assertTestPackedMessage($to);
+ }
+
+ public function testUnpackedEncode()
+ {
+ $from = new TestUnpackedMessage();
+ TestUtil::setTestPackedMessage($from);
+ $this->assertSame(TestUtil::getGoldenTestUnpackedMessage(),
+ $from->encode());
+ }
+
+ public function testUnpackedDecodePacked()
+ {
+ $to = new TestUnpackedMessage();
+ $to->decode(TestUtil::getGoldenTestPackedMessage());
+ TestUtil::assertTestPackedMessage($to);
+ }
+
+ public function testUnpackedDecodeUnpacked()
+ {
+ $to = new TestUnpackedMessage();
+ $to->decode(TestUtil::getGoldenTestUnpackedMessage());
+ TestUtil::assertTestPackedMessage($to);
+ }
+}
diff --git a/php/tests/generated_class_test.php b/php/tests/generated_class_test.php
new file mode 100644
index 00000000..b3ecd3a1
--- /dev/null
+++ b/php/tests/generated_class_test.php
@@ -0,0 +1,611 @@
+<?php
+
+require_once('test.pb.php');
+require_once('test_no_namespace.pb.php');
+require_once('test_util.php');
+
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBType;
+use Foo\TestEnum;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+
+class GeneratedClassTest extends PHPUnit_Framework_TestCase
+{
+
+ #########################################################
+ # Test field accessors.
+ #########################################################
+
+ public function testSetterGetter()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt32(1);
+ $this->assertSame(1, $m->getOptionalInt32());
+ }
+
+ #########################################################
+ # Test int32 field.
+ #########################################################
+
+ public function testInt32Field()
+ {
+ $m = new TestMessage();
+
+ // Set integer.
+ $m->setOptionalInt32(MAX_INT32);
+ $this->assertSame(MAX_INT32, $m->getOptionalInt32());
+ $m->setOptionalInt32(MIN_INT32);
+ $this->assertSame(MIN_INT32, $m->getOptionalInt32());
+
+ // Set float.
+ $m->setOptionalInt32(1.1);
+ $this->assertSame(1, $m->getOptionalInt32());
+ $m->setOptionalInt32(MAX_INT32_FLOAT);
+ $this->assertSame(MAX_INT32, $m->getOptionalInt32());
+ $m->setOptionalInt32(MIN_INT32_FLOAT);
+ $this->assertSame(MIN_INT32, $m->getOptionalInt32());
+
+ // Set string.
+ $m->setOptionalInt32('2');
+ $this->assertSame(2, $m->getOptionalInt32());
+ $m->setOptionalInt32('3.1');
+ $this->assertSame(3, $m->getOptionalInt32());
+ $m->setOptionalInt32(MAX_INT32_STRING);
+ $this->assertSame(MAX_INT32, $m->getOptionalInt32());
+ $m->setOptionalInt32(MIN_INT32_STRING);
+ $this->assertSame(MIN_INT32, $m->getOptionalInt32());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt32(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt32('abc');
+ }
+
+ #########################################################
+ # Test uint32 field.
+ #########################################################
+
+ public function testUint32Field()
+ {
+ $m = new TestMessage();
+
+ // Set integer.
+ $m->setOptionalUint32(MAX_UINT32);
+ $this->assertSame(-1, $m->getOptionalUint32());
+ $m->setOptionalUint32(-1);
+ $this->assertSame(-1, $m->getOptionalUint32());
+ $m->setOptionalUint32(MIN_UINT32);
+ $this->assertSame(MIN_INT32, $m->getOptionalUint32());
+
+ // Set float.
+ $m->setOptionalUint32(1.1);
+ $this->assertSame(1, $m->getOptionalUint32());
+ $m->setOptionalUint32(MAX_UINT32_FLOAT);
+ $this->assertSame(-1, $m->getOptionalUint32());
+ $m->setOptionalUint32(-1.0);
+ $this->assertSame(-1, $m->getOptionalUint32());
+ $m->setOptionalUint32(MIN_UINT32_FLOAT);
+ $this->assertSame(MIN_INT32, $m->getOptionalUint32());
+
+ // Set string.
+ $m->setOptionalUint32('2');
+ $this->assertSame(2, $m->getOptionalUint32());
+ $m->setOptionalUint32('3.1');
+ $this->assertSame(3, $m->getOptionalUint32());
+ $m->setOptionalUint32(MAX_UINT32_STRING);
+ $this->assertSame(-1, $m->getOptionalUint32());
+ $m->setOptionalUint32('-1.0');
+ $this->assertSame(-1, $m->getOptionalUint32());
+ $m->setOptionalUint32(MIN_UINT32_STRING);
+ $this->assertSame(MIN_INT32, $m->getOptionalUint32());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint32(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint32('abc');
+ }
+
+ #########################################################
+ # Test int64 field.
+ #########################################################
+
+ public function testInt64Field()
+ {
+ $m = new TestMessage();
+
+ // Set integer.
+ $m->setOptionalInt64(MAX_INT64);
+ $this->assertSame(MAX_INT64, $m->getOptionalInt64());
+ $m->setOptionalInt64(MIN_INT64);
+ $this->assertEquals(MIN_INT64, $m->getOptionalInt64());
+
+ // Set float.
+ $m->setOptionalInt64(1.1);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('1', $m->getOptionalInt64());
+ } else {
+ $this->assertSame(1, $m->getOptionalInt64());
+ }
+
+ // Set string.
+ $m->setOptionalInt64('2');
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('2', $m->getOptionalInt64());
+ } else {
+ $this->assertSame(2, $m->getOptionalInt64());
+ }
+
+ $m->setOptionalInt64('3.1');
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('3', $m->getOptionalInt64());
+ } else {
+ $this->assertSame(3, $m->getOptionalInt64());
+ }
+
+ $m->setOptionalInt64(MAX_INT64_STRING);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_INT64_STRING, $m->getOptionalInt64());
+ } else {
+ $this->assertSame(MAX_INT64, $m->getOptionalInt64());
+ }
+
+ $m->setOptionalInt64(MIN_INT64_STRING);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MIN_INT64_STRING, $m->getOptionalInt64());
+ } else {
+ $this->assertSame(MIN_INT64, $m->getOptionalInt64());
+ }
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt64(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalInt64('abc');
+ }
+
+ #########################################################
+ # Test uint64 field.
+ #########################################################
+
+ public function testUint64Field()
+ {
+ $m = new TestMessage();
+
+ // Set integer.
+ $m->setOptionalUint64(MAX_UINT64);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_UINT64_STRING, $m->getOptionalUint64());
+ } else {
+ $this->assertSame(MAX_UINT64, $m->getOptionalUint64());
+ }
+
+ // Set float.
+ $m->setOptionalUint64(1.1);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('1', $m->getOptionalUint64());
+ } else {
+ $this->assertSame(1, $m->getOptionalUint64());
+ }
+
+ // Set string.
+ $m->setOptionalUint64('2');
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('2', $m->getOptionalUint64());
+ } else {
+ $this->assertSame(2, $m->getOptionalUint64());
+ }
+
+ $m->setOptionalUint64('3.1');
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('3', $m->getOptionalUint64());
+ } else {
+ $this->assertSame(3, $m->getOptionalUint64());
+ }
+
+ $m->setOptionalUint64(MAX_UINT64_STRING);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_UINT64_STRING, $m->getOptionalUint64());
+ } else {
+ $this->assertSame(MAX_UINT64, $m->getOptionalUint64());
+ }
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64FieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint64(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64FieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalUint64('abc');
+ }
+
+ #########################################################
+ # Test enum field.
+ #########################################################
+
+ public function testEnumField()
+ {
+ $m = new TestMessage();
+
+ // Set enum.
+ $m->setOptionalEnum(TestEnum::ONE);
+ $this->assertEquals(TestEnum::ONE, $m->getOptionalEnum());
+
+ // Set integer.
+ $m->setOptionalEnum(1);
+ $this->assertEquals(TestEnum::ONE, $m->getOptionalEnum());
+
+ // Set float.
+ $m->setOptionalEnum(1.1);
+ $this->assertEquals(TestEnum::ONE, $m->getOptionalEnum());
+
+ // Set string.
+ $m->setOptionalEnum("1");
+ $this->assertEquals(TestEnum::ONE, $m->getOptionalEnum());
+ }
+
+ #########################################################
+ # Test float field.
+ #########################################################
+
+ public function testFloatField()
+ {
+ $m = new TestMessage();
+
+ // Set integer.
+ $m->setOptionalFloat(1);
+ $this->assertEquals(1.0, $m->getOptionalFloat(), '', MAX_FLOAT_DIFF);
+
+ // Set float.
+ $m->setOptionalFloat(1.1);
+ $this->assertEquals(1.1, $m->getOptionalFloat(), '', MAX_FLOAT_DIFF);
+
+ // Set string.
+ $m->setOptionalFloat('2');
+ $this->assertEquals(2.0, $m->getOptionalFloat(), '', MAX_FLOAT_DIFF);
+ $m->setOptionalFloat('3.1');
+ $this->assertEquals(3.1, $m->getOptionalFloat(), '', MAX_FLOAT_DIFF);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatFieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalFloat(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatFieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalFloat('abc');
+ }
+
+ #########################################################
+ # Test double field.
+ #########################################################
+
+ public function testDoubleField()
+ {
+ $m = new TestMessage();
+
+ // Set integer.
+ $m->setOptionalDouble(1);
+ $this->assertEquals(1.0, $m->getOptionalDouble(), '', MAX_FLOAT_DIFF);
+
+ // Set float.
+ $m->setOptionalDouble(1.1);
+ $this->assertEquals(1.1, $m->getOptionalDouble(), '', MAX_FLOAT_DIFF);
+
+ // Set string.
+ $m->setOptionalDouble('2');
+ $this->assertEquals(2.0, $m->getOptionalDouble(), '', MAX_FLOAT_DIFF);
+ $m->setOptionalDouble('3.1');
+ $this->assertEquals(3.1, $m->getOptionalDouble(), '', MAX_FLOAT_DIFF);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleFieldInvalidTypeFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalDouble(new TestMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleFieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalDouble('abc');
+ }
+
+ #########################################################
+ # Test bool field.
+ #########################################################
+
+ public function testBoolField()
+ {
+ $m = new TestMessage();
+
+ // Set bool.
+ $m->setOptionalBool(true);
+ $this->assertSame(true, $m->getOptionalBool());
+
+ // Set integer.
+ $m->setOptionalBool(-1);
+ $this->assertSame(true, $m->getOptionalBool());
+
+ // Set float.
+ $m->setOptionalBool(1.1);
+ $this->assertSame(true, $m->getOptionalBool());
+
+ // Set string.
+ $m->setOptionalBool('');
+ $this->assertSame(false, $m->getOptionalBool());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolFieldInvalidStringFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalBool(new TestMessage());
+ }
+
+ #########################################################
+ # Test string field.
+ #########################################################
+
+ public function testStringField()
+ {
+ $m = new TestMessage();
+
+ // Set string.
+ $m->setOptionalString('abc');
+ $this->assertSame('abc', $m->getOptionalString());
+
+ // Set integer.
+ $m->setOptionalString(1);
+ $this->assertSame('1', $m->getOptionalString());
+
+ // Set double.
+ $m->setOptionalString(1.1);
+ $this->assertSame('1.1', $m->getOptionalString());
+
+ // Set bool.
+ $m->setOptionalString(true);
+ $this->assertSame('1', $m->getOptionalString());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringFieldInvalidUTF8Fail()
+ {
+ $m = new TestMessage();
+ $hex = hex2bin("ff");
+ $m->setOptionalString($hex);
+ }
+
+ #########################################################
+ # Test bytes field.
+ #########################################################
+
+ public function testBytesField()
+ {
+ $m = new TestMessage();
+
+ // Set string.
+ $m->setOptionalBytes('abc');
+ $this->assertSame('abc', $m->getOptionalBytes());
+
+ // Set integer.
+ $m->setOptionalBytes(1);
+ $this->assertSame('1', $m->getOptionalBytes());
+
+ // Set double.
+ $m->setOptionalBytes(1.1);
+ $this->assertSame('1.1', $m->getOptionalBytes());
+
+ // Set bool.
+ $m->setOptionalBytes(true);
+ $this->assertSame('1', $m->getOptionalBytes());
+ }
+
+ public function testBytesFieldInvalidUTF8Success()
+ {
+ $m = new TestMessage();
+ $hex = hex2bin("ff");
+ $m->setOptionalBytes($hex);
+ }
+
+ #########################################################
+ # Test message field.
+ #########################################################
+
+ public function testMessageField()
+ {
+ $m = new TestMessage();
+
+ $sub_m = new TestMessage_Sub();
+ $sub_m->setA(1);
+ $m->setOptionalMessage($sub_m);
+ $this->assertSame(1, $m->getOptionalMessage()->getA());
+
+ $null = null;
+ $m->setOptionalMessage($null);
+ $this->assertNull($m->getOptionalMessage());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageFieldWrongTypeFail()
+ {
+ $m = new TestMessage();
+ $a = 1;
+ $m->setOptionalMessage($a);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageFieldWrongClassFail()
+ {
+ $m = new TestMessage();
+ $m->setOptionalMessage(new TestMessage());
+ }
+
+ #########################################################
+ # Test repeated field.
+ #########################################################
+
+ public function testRepeatedField()
+ {
+ $m = new TestMessage();
+
+ $repeated_int32 = new RepeatedField(GPBType::INT32);
+ $m->setRepeatedInt32($repeated_int32);
+ $this->assertSame($repeated_int32, $m->getRepeatedInt32());
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongTypeFail()
+ {
+ $m = new TestMessage();
+ $a = 1;
+ $m->setRepeatedInt32($a);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongObjectFail()
+ {
+ $m = new TestMessage();
+ $m->setRepeatedInt32($m);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongRepeatedTypeFail()
+ {
+ $m = new TestMessage();
+
+ $repeated_int32 = new RepeatedField(GPBType::UINT32);
+ $m->setRepeatedInt32($repeated_int32);
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testRepeatedFieldWrongRepeatedMessageClassFail()
+ {
+ $m = new TestMessage();
+
+ $repeated_message = new RepeatedField(GPBType::MESSAGE,
+ TestMessage::class);
+ $m->setRepeatedMessage($repeated_message);
+ }
+
+ #########################################################
+ # Test oneof field.
+ #########################################################
+
+ public function testOneofField() {
+ $m = new TestMessage();
+
+ $m->setOneofInt32(1);
+ $this->assertSame(1, $m->getOneofInt32());
+ $this->assertSame(0.0, $m->getOneofFloat());
+ $this->assertSame('', $m->getOneofString());
+ $this->assertSame(NULL, $m->getOneofMessage());
+
+ $m->setOneofFloat(2.0);
+ $this->assertSame(0, $m->getOneofInt32());
+ $this->assertSame(2.0, $m->getOneofFloat());
+ $this->assertSame('', $m->getOneofString());
+ $this->assertSame(NULL, $m->getOneofMessage());
+
+ $m->setOneofString('abc');
+ $this->assertSame(0, $m->getOneofInt32());
+ $this->assertSame(0.0, $m->getOneofFloat());
+ $this->assertSame('abc', $m->getOneofString());
+ $this->assertSame(NULL, $m->getOneofMessage());
+
+ $sub_m = new TestMessage_Sub();
+ $sub_m->setA(1);
+ $m->setOneofMessage($sub_m);
+ $this->assertSame(0, $m->getOneofInt32());
+ $this->assertSame(0.0, $m->getOneofFloat());
+ $this->assertSame('', $m->getOneofString());
+ $this->assertSame(1, $m->getOneofMessage()->getA());
+ }
+
+ #########################################################
+ # Test oneof field.
+ #########################################################
+
+ public function testMessageWithoutNamespace() {
+ $m = new NoNameSpace();
+ }
+}
diff --git a/php/tests/map_field_test.php b/php/tests/map_field_test.php
new file mode 100644
index 00000000..4e42361d
--- /dev/null
+++ b/php/tests/map_field_test.php
@@ -0,0 +1,680 @@
+<?php
+
+require_once('test.pb.php');
+require_once('test_util.php');
+
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\MapField;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+
+class MapFieldTest extends PHPUnit_Framework_TestCase {
+
+ #########################################################
+ # Test int32 field.
+ #########################################################
+
+ public function testInt32() {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+
+ // Test integer argument.
+ $arr[MAX_INT32] = MAX_INT32;
+ $this->assertSame(MAX_INT32, $arr[MAX_INT32]);
+ $arr[MIN_INT32] = MIN_INT32;
+ $this->assertSame(MIN_INT32, $arr[MIN_INT32]);
+ $this->assertEquals(2, count($arr));
+ $this->assertTrue(isset($arr[MAX_INT32]));
+ $this->assertTrue(isset($arr[MIN_INT32]));
+ unset($arr[MAX_INT32]);
+ unset($arr[MIN_INT32]);
+ $this->assertEquals(0, count($arr));
+
+ // Test float argument.
+ $arr[1.9] = 1.9;
+ $arr[2.1] = 2.1;
+ $this->assertSame(1, $arr[1]);
+ $this->assertSame(2, $arr[2]);
+ $arr[MAX_INT32_FLOAT] = MAX_INT32_FLOAT;
+ $this->assertSame(MAX_INT32, $arr[MAX_INT32]);
+ $arr[MIN_INT32_FLOAT] = MIN_INT32_FLOAT;
+ $this->assertSame(MIN_INT32, $arr[MIN_INT32]);
+ $this->assertEquals(4, count($arr));
+ unset($arr[1.9]);
+ unset($arr[2.9]);
+ unset($arr[MAX_INT32_FLOAT]);
+ unset($arr[MIN_INT32_FLOAT]);
+ $this->assertEquals(0, count($arr));
+
+ // Test string argument.
+ $arr['2'] = '2';
+ $this->assertSame(2, $arr[2]);
+ $arr['3.1'] = '3.1';
+ $this->assertSame(3, $arr[3]);
+ $arr[MAX_INT32_STRING] = MAX_INT32_STRING;
+ $this->assertSame(MAX_INT32, $arr[MAX_INT32]);
+ $this->assertEquals(3, count($arr));
+ unset($arr['2']);
+ unset($arr['3.1']);
+ unset($arr[MAX_INT32_STRING]);
+ $this->assertEquals(0, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr ['abc']= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr [new TestMessage_Sub()]= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt32SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT32, GPBType::INT32);
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test uint32 field.
+ #########################################################
+
+ public function testUint32() {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+
+ // Test integer argument.
+ $arr[MAX_UINT32] = MAX_UINT32;
+ $this->assertSame(-1, $arr[-1]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[MAX_UINT32]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[-1] = -1;
+ $this->assertSame(-1, $arr[-1]);
+ $arr[MIN_UINT32] = MIN_UINT32;
+ $this->assertSame(MIN_UINT32, $arr[MIN_UINT32]);
+ $this->assertEquals(2, count($arr));
+ unset($arr[-1]);
+ unset($arr[MIN_UINT32]);
+ $this->assertEquals(0, count($arr));
+
+ // Test float argument.
+ $arr[MAX_UINT32_FLOAT] = MAX_UINT32_FLOAT;
+ $this->assertSame(-1, $arr[-1]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[MAX_UINT32_FLOAT]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[3.1] = 3.1;
+ $this->assertSame(3, $arr[3]);
+ $arr[-1.0] = -1.0;
+ $this->assertSame(-1, $arr[-1]);
+ $arr[MIN_UINT32_FLOAT] = MIN_UINT32_FLOAT;
+ $this->assertSame(MIN_UINT32, $arr[MIN_UINT32]);
+ $this->assertEquals(3, count($arr));
+ unset($arr[3.1]);
+ unset($arr[-1.0]);
+ unset($arr[MIN_UINT32_FLOAT]);
+ $this->assertEquals(0, count($arr));
+
+ // Test string argument.
+ $arr[MAX_UINT32_STRING] = MAX_UINT32_STRING;
+ $this->assertSame(-1, $arr[-1]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[MAX_UINT32_STRING]);
+ $this->assertEquals(0, count($arr));
+
+ $arr['7'] = '7';
+ $this->assertSame(7, $arr[7]);
+ $arr['3.1'] = '3.1';
+ $this->assertSame(3, $arr[3]);
+ $arr['-1.0'] = '-1.0';
+ $this->assertSame(-1, $arr[-1]);
+ $arr[MIN_UINT32_STRING] = MIN_UINT32_STRING;
+ $this->assertSame(MIN_UINT32, $arr[MIN_UINT32]);
+ $this->assertEquals(4, count($arr));
+ unset($arr['7']);
+ unset($arr['3.1']);
+ unset($arr['-1.0']);
+ unset($arr[MIN_UINT32_STRING]);
+ $this->assertEquals(0, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr ['abc']= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr [new TestMessage_Sub()]= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint32SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::UINT32, GPBType::UINT32);
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test int64 field.
+ #########################################################
+
+ public function testInt64() {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+
+ // Test integer argument.
+ $arr[MAX_INT64] = MAX_INT64;
+ $arr[MIN_INT64] = MIN_INT64;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_INT64_STRING, $arr[MAX_INT64_STRING]);
+ $this->assertSame(MIN_INT64_STRING, $arr[MIN_INT64_STRING]);
+ } else {
+ $this->assertSame(MAX_INT64, $arr[MAX_INT64]);
+ $this->assertSame(MIN_INT64, $arr[MIN_INT64]);
+ }
+ $this->assertEquals(2, count($arr));
+ unset($arr[MAX_INT64]);
+ unset($arr[MIN_INT64]);
+ $this->assertEquals(0, count($arr));
+
+ // Test float argument.
+ $arr[1.1] = 1.1;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('1', $arr['1']);
+ } else {
+ $this->assertSame(1, $arr[1]);
+ }
+ $this->assertEquals(1, count($arr));
+ unset($arr[1.1]);
+ $this->assertEquals(0, count($arr));
+
+ // Test string argument.
+ $arr['2'] = '2';
+ $arr['3.1'] = '3.1';
+ $arr[MAX_INT64_STRING] = MAX_INT64_STRING;
+ $arr[MIN_INT64_STRING] = MIN_INT64_STRING;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('2', $arr['2']);
+ $this->assertSame('3', $arr['3']);
+ $this->assertSame(MAX_INT64_STRING, $arr[MAX_INT64_STRING]);
+ $this->assertSame(MIN_INT64_STRING, $arr[MIN_INT64_STRING]);
+ } else {
+ $this->assertSame(2, $arr[2]);
+ $this->assertSame(3, $arr[3]);
+ $this->assertSame(MAX_INT64, $arr[MAX_INT64]);
+ $this->assertSame(MIN_INT64, $arr[MIN_INT64]);
+ }
+ $this->assertEquals(4, count($arr));
+ unset($arr['2']);
+ unset($arr['3.1']);
+ unset($arr[MAX_INT64_STRING]);
+ unset($arr[MIN_INT64_STRING]);
+ $this->assertEquals(0, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr ['abc']= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr [new TestMessage_Sub()]= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testInt64SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::INT64);
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test uint64 field.
+ #########################################################
+
+ public function testUint64() {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+
+ // Test integer argument.
+ $arr[MAX_UINT64] = MAX_UINT64;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame(MAX_UINT64_STRING, $arr[MAX_UINT64_STRING]);
+ } else {
+ $this->assertSame(MAX_UINT64, $arr[MAX_UINT64]);
+ }
+ $this->assertEquals(1, count($arr));
+ unset($arr[MAX_UINT64]);
+ $this->assertEquals(0, count($arr));
+
+ // Test float argument.
+ $arr[1.1] = 1.1;
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('1', $arr['1']);
+ } else {
+ $this->assertSame(1, $arr[1]);
+ }
+ $this->assertEquals(1, count($arr));
+ unset($arr[1.1]);
+ $this->assertEquals(0, count($arr));
+
+ // Test string argument.
+ $arr['2'] = '2';
+ $arr['3.1'] = '3.1';
+ $arr[MAX_UINT64_STRING] = MAX_UINT64_STRING;
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('2', $arr['2']);
+ $this->assertSame('3', $arr['3']);
+ $this->assertSame(MAX_UINT64_STRING, $arr[MAX_UINT64_STRING]);
+ } else {
+ $this->assertSame(2, $arr[2]);
+ $this->assertSame(3, $arr[3]);
+ $this->assertSame(MAX_UINT64, $arr[MAX_UINT64]);
+ }
+
+ $this->assertEquals(3, count($arr));
+ unset($arr['2']);
+ unset($arr['3.1']);
+ unset($arr[MAX_UINT64_STRING]);
+ $this->assertEquals(0, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetStringKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr ['abc']= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetStringValueFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr [new TestMessage_Sub()]= 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testUint64SetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::UINT64, GPBType::UINT64);
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test float field.
+ #########################################################
+
+ public function testFloat() {
+ $arr = new MapField(GPBType::INT32, GPBType::FLOAT);
+
+ // Test set.
+ $arr[0] = 1;
+ $this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
+
+ $arr[1] = 1.1;
+ $this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
+
+ $arr[2] = '2';
+ $this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
+ $arr[3] = '3.1';
+ $this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
+
+ $this->assertEquals(4, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatSetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::FLOAT);
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testFloatSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::FLOAT);
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test double field.
+ #########################################################
+
+ public function testDouble() {
+ $arr = new MapField(GPBType::INT32, GPBType::DOUBLE);
+
+ // Test set.
+ $arr[0] = 1;
+ $this->assertEquals(1.0, $arr[0], '', MAX_FLOAT_DIFF);
+
+ $arr[1] = 1.1;
+ $this->assertEquals(1.1, $arr[1], '', MAX_FLOAT_DIFF);
+
+ $arr[2] = '2';
+ $this->assertEquals(2.0, $arr[2], '', MAX_FLOAT_DIFF);
+ $arr[3] = '3.1';
+ $this->assertEquals(3.1, $arr[3], '', MAX_FLOAT_DIFF);
+
+ $this->assertEquals(4, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetStringValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
+ $arr [0]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testDoubleSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::INT64, GPBType::DOUBLE);
+ $arr [0]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test bool field.
+ #########################################################
+
+ public function testBool() {
+ $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
+
+ // Test boolean.
+ $arr[True] = True;
+ $this->assertSame(True, $arr[True]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[True]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[False] = False;
+ $this->assertSame(False, $arr[False]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[False]);
+ $this->assertEquals(0, count($arr));
+
+ // Test integer.
+ $arr[-1] = -1;
+ $this->assertSame(True, $arr[True]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[-1]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[0] = 0;
+ $this->assertSame(False, $arr[False]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[0]);
+ $this->assertEquals(0, count($arr));
+
+ // Test float.
+ $arr[1.1] = 1.1;
+ $this->assertSame(True, $arr[True]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[1.1]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[0.0] = 0.0;
+ $this->assertSame(False, $arr[False]);
+ $this->assertEquals(1, count($arr));
+ unset($arr[0.0]);
+ $this->assertEquals(0, count($arr));
+
+ // Test string.
+ $arr['a'] = 'a';
+ $this->assertSame(True, $arr[True]);
+ $this->assertEquals(1, count($arr));
+ unset($arr['a']);
+ $this->assertEquals(0, count($arr));
+
+ $arr[''] = '';
+ $this->assertSame(False, $arr[False]);
+ $this->assertEquals(1, count($arr));
+ unset($arr['']);
+ $this->assertEquals(0, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolSetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
+ $arr [new TestMessage_Sub()]= true;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testBoolSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::BOOL, GPBType::BOOL);
+ $arr [true]= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test string field.
+ #########################################################
+
+ public function testString() {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+
+ // Test set.
+ $arr['abc'] = 'abc';
+ $this->assertSame('abc', $arr['abc']);
+ $this->assertEquals(1, count($arr));
+ unset($arr['abc']);
+ $this->assertEquals(0, count($arr));
+
+ $arr[1] = 1;
+ $this->assertSame('1', $arr['1']);
+ $this->assertEquals(1, count($arr));
+ unset($arr[1]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[1.1] = 1.1;
+ $this->assertSame('1.1', $arr['1.1']);
+ $this->assertEquals(1, count($arr));
+ unset($arr[1.1]);
+ $this->assertEquals(0, count($arr));
+
+ $arr[True] = True;
+ $this->assertSame('1', $arr['1']);
+ $this->assertEquals(1, count($arr));
+ unset($arr[True]);
+ $this->assertEquals(0, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetInvalidUTF8KeyFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr[hex2bin("ff")]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetInvalidUTF8ValueFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr ['abc']= hex2bin("ff");
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetMessageKeyFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr [new TestMessage_Sub()]= 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testStringSetMessageValueFail()
+ {
+ $arr = new MapField(GPBType::STRING, GPBType::STRING);
+ $arr ['abc']= new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test message field.
+ #########################################################
+
+ public function testMessage() {
+ $arr = new MapField(GPBType::INT32,
+ GPBType::MESSAGE, TestMessage_Sub::class);
+
+ // Test append.
+ $sub_m = new TestMessage_Sub();
+ $sub_m->setA(1);
+ $arr[0] = $sub_m;
+ $this->assertSame(1, $arr[0]->getA());
+
+ $null = NULL;
+ $arr[1] = $null;
+ $this->assertNull($arr[1]);
+
+ $this->assertEquals(2, count($arr));
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetIntValueFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $arr[0] = 0;
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetStringValueFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $arr[0] = 'abc';
+ }
+
+ /**
+ * @expectedException PHPUnit_Framework_Error
+ */
+ public function testMessageSetOtherMessageValueFail()
+ {
+ $arr =
+ new MapField(GPBType::INT32, GPBType::MESSAGE, TestMessage::class);
+ $arr[0] = new TestMessage_Sub();
+ }
+
+ #########################################################
+ # Test memory leak
+ #########################################################
+
+ // TODO(teboring): Add it back.
+ // public function testCycleLeak()
+ // {
+ // $arr = new MapField(GPBType::INT32,
+ // GPBType::MESSAGE, TestMessage::class);
+ // $arr [0]= new TestMessage;
+ // $arr[0]->SetMapRecursive($arr);
+
+ // // Clean up memory before test.
+ // gc_collect_cycles();
+ // $start = memory_get_usage();
+ // unset($arr);
+
+ // // Explicitly trigger garbage collection.
+ // gc_collect_cycles();
+
+ // $end = memory_get_usage();
+ // $this->assertLessThan($start, $end);
+ // }
+}
diff --git a/php/tests/memory_leak_test.php b/php/tests/memory_leak_test.php
new file mode 100644
index 00000000..ec54597b
--- /dev/null
+++ b/php/tests/memory_leak_test.php
@@ -0,0 +1,73 @@
+<?php
+
+# phpunit has memory leak by itself. Thus, it cannot be used to test memory leak.
+
+require_once('test.pb.php');
+require_once('test_util.php');
+
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBType;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+
+$from = new TestMessage();
+TestUtil::setTestMessage($from);
+TestUtil::assertTestMessage($from);
+
+$data = $from->encode();
+
+$to = new TestMessage();
+$to->decode($data);
+
+TestUtil::assertTestMessage($to);
+
+$from->setRecursive($from);
+
+$arr = new RepeatedField(GPBType::MESSAGE, TestMessage::class);
+$arr []= new TestMessage;
+$arr[0]->SetRepeatedRecursive($arr);
+
+// Test oneof fields.
+$m = new TestMessage();
+
+$m->setOneofInt32(1);
+assert(1 === $m->getOneofInt32());
+assert(0.0 === $m->getOneofFloat());
+assert('' === $m->getOneofString());
+assert(NULL === $m->getOneofMessage());
+$data = $m->encode();
+$n = new TestMessage();
+$n->decode($data);
+assert(1 === $n->getOneofInt32());
+
+$m->setOneofFloat(2.0);
+assert(0 === $m->getOneofInt32());
+assert(2.0 === $m->getOneofFloat());
+assert('' === $m->getOneofString());
+assert(NULL === $m->getOneofMessage());
+$data = $m->encode();
+$n = new TestMessage();
+$n->decode($data);
+assert(2.0 === $n->getOneofFloat());
+
+$m->setOneofString('abc');
+assert(0 === $m->getOneofInt32());
+assert(0.0 === $m->getOneofFloat());
+assert('abc' === $m->getOneofString());
+assert(NULL === $m->getOneofMessage());
+$data = $m->encode();
+$n = new TestMessage();
+$n->decode($data);
+assert('abc' === $n->getOneofString());
+
+$sub_m = new TestMessage_Sub();
+$sub_m->setA(1);
+$m->setOneofMessage($sub_m);
+assert(0 === $m->getOneofInt32());
+assert(0.0 === $m->getOneofFloat());
+assert('' === $m->getOneofString());
+assert(1 === $m->getOneofMessage()->getA());
+$data = $m->encode();
+$n = new TestMessage();
+$n->decode($data);
+assert(1 === $n->getOneofMessage()->getA());
diff --git a/php/tests/php_implementation_test.php b/php/tests/php_implementation_test.php
new file mode 100644
index 00000000..485956cc
--- /dev/null
+++ b/php/tests/php_implementation_test.php
@@ -0,0 +1,481 @@
+<?php
+
+require_once('test.pb.php');
+require_once('test_base.php');
+require_once('test_util.php');
+
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+use Foo\TestPackedMessage;
+use Google\Protobuf\Internal\InputStream;
+use Google\Protobuf\Internal\FileDescriptorSet;
+use Google\Protobuf\Internal\GPBLabel;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\GPBWire;
+use Google\Protobuf\Internal\OutputStream;
+
+class ImplementationTest extends TestBase
+{
+
+ public function testReadInt32()
+ {
+ $value = null;
+
+ // Positive number.
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readInt32($input, $value);
+ $this->assertSame(1, $value);
+
+ // Negative number.
+ $input = new InputStream(hex2bin("ffffffff0f"));
+ GPBWire::readInt32($input, $value);
+ $this->assertSame(-1, $value);
+
+ // Discard overflow bits.
+ $input = new InputStream(hex2bin("ffffffff7f"));
+ GPBWire::readInt32($input, $value);
+ $this->assertSame(-1, $value);
+ }
+
+ public function testReadUint32()
+ {
+ $value = null;
+
+ // Positive number.
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readUint32($input, $value);
+ $this->assertSame(1, $value);
+
+ // Max uint32.
+ $input = new InputStream(hex2bin("ffffffff0f"));
+ GPBWire::readUint32($input, $value);
+ $this->assertSame(-1, $value);
+
+ // Discard overflow bits.
+ $input = new InputStream(hex2bin("ffffffff7f"));
+ GPBWire::readUint32($input, $value);
+ $this->assertSame(-1, $value);
+ }
+
+ public function testReadInt64()
+ {
+ $value = null;
+
+ // Positive number.
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readInt64($input, $value);
+ $this->assertEquals(1, $value);
+
+ // Negative number.
+ $input = new InputStream(hex2bin("ffffffffffffffffff01"));
+ GPBWire::readInt64($input, $value);
+ $this->assertEquals(-1, $value);
+
+ // Discard overflow bits.
+ $input = new InputStream(hex2bin("ffffffffffffffffff0f"));
+ GPBWire::readInt64($input, $value);
+ $this->assertEquals(-1, $value);
+ }
+
+ public function testReadUint64()
+ {
+ $value = null;
+
+ // Positive number.
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readUint64($input, $value);
+ $this->assertEquals(1, $value);
+
+ // Negative number.
+ $input = new InputStream(hex2bin("FFFFFFFFFFFFFFFFFF01"));
+ GPBWire::readUint64($input, $value);
+ $this->assertEquals(-1, $value);
+
+ // Discard overflow bits.
+ $input = new InputStream(hex2bin("FFFFFFFFFFFFFFFFFF0F"));
+ GPBWire::readUint64($input, $value);
+ $this->assertEquals(-1, $value);
+ }
+
+ public function testReadSint32()
+ {
+ $value = null;
+
+ $input = new InputStream(hex2bin("00"));
+ GPBWire::readSint32($input, $value);
+ $this->assertSame(0, $value);
+
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readSint32($input, $value);
+ $this->assertSame(-1, $value);
+
+ $input = new InputStream(hex2bin("02"));
+ GPBWire::readSint32($input, $value);
+ $this->assertSame(1, $value);
+ }
+
+ public function testReadSint64()
+ {
+ $value = null;
+
+ $input = new InputStream(hex2bin("00"));
+ GPBWire::readSint64($input, $value);
+ $this->assertEquals(0, $value);
+
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readSint64($input, $value);
+ $this->assertEquals(-1, $value);
+
+ $input = new InputStream(hex2bin("02"));
+ GPBWire::readSint64($input, $value);
+ $this->assertEquals(1, $value);
+ }
+
+ public function testReadFixed32()
+ {
+ $value = null;
+ $input = new InputStream(hex2bin("12345678"));
+ GPBWire::readFixed32($input, $value);
+ $this->assertSame(0x78563412, $value);
+ }
+
+ public function testReadFixed64()
+ {
+ $value = null;
+ $input = new InputStream(hex2bin("1234567812345678"));
+ GPBWire::readFixed64($input, $value);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame("8671175386481439762", $value);
+ } else {
+ $this->assertSame(0x7856341278563412, $value);
+ }
+ }
+
+ public function testReadSfixed32()
+ {
+ $value = null;
+ $input = new InputStream(hex2bin("12345678"));
+ GPBWire::readSfixed32($input, $value);
+ $this->assertSame(0x78563412, $value);
+ }
+
+ public function testReadFloat()
+ {
+ $value = null;
+ $input = new InputStream(hex2bin("0000803F"));
+ GPBWire::readFloat($input, $value);
+ $this->assertSame(1.0, $value);
+ }
+
+ public function testReadBool()
+ {
+ $value = null;
+
+ $input = new InputStream(hex2bin("00"));
+ GPBWire::readBool($input, $value);
+ $this->assertSame(false, $value);
+
+ $input = new InputStream(hex2bin("01"));
+ GPBWire::readBool($input, $value);
+ $this->assertSame(true, $value);
+ }
+
+ public function testReadDouble()
+ {
+ $value = null;
+ $input = new InputStream(hex2bin("000000000000F03F"));
+ GPBWire::readDouble($input, $value);
+ $this->assertSame(1.0, $value);
+ }
+
+ public function testReadSfixed64()
+ {
+ $value = null;
+ $input = new InputStream(hex2bin("1234567812345678"));
+ GPBWire::readSfixed64($input, $value);
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame("8671175386481439762", $value);
+ } else {
+ $this->assertSame(0x7856341278563412, $value);
+ }
+ }
+
+ public function testZigZagEncodeDecode()
+ {
+ $this->assertSame(0, GPBWire::zigZagEncode32(0));
+ $this->assertSame(1, GPBWire::zigZagEncode32(-1));
+ $this->assertSame(2, GPBWire::zigZagEncode32(1));
+ $this->assertSame(3, GPBWire::zigZagEncode32(-2));
+ $this->assertSame(0x7FFFFFFE, GPBWire::zigZagEncode32(0x3FFFFFFF));
+ $this->assertSame(0x7FFFFFFF, GPBWire::zigZagEncode32(0xC0000000));
+ $this->assertSame(-2, GPBWire::zigZagEncode32(0x7FFFFFFF));
+ $this->assertSame(-1, GPBWire::zigZagEncode32(0x80000000));
+
+ $this->assertSame(0, GPBWire::zigZagDecode32(0));
+ $this->assertSame(-1, GPBWire::zigZagDecode32(1));
+ $this->assertSame(1, GPBWire::zigZagDecode32(2));
+ $this->assertSame(-2, GPBWire::zigZagDecode32(3));
+ $this->assertSame(0x3FFFFFFF, GPBWire::zigZagDecode32(0x7FFFFFFE));
+ $this->assertSame(-1073741824, GPBWire::zigZagDecode32(0x7FFFFFFF));
+ $this->assertSame(0x7FFFFFFF, GPBWire::zigZagDecode32(0xFFFFFFFE));
+ $this->assertSame((int)-2147483648,GPBWire::zigZagDecode32(0xFFFFFFFF));
+
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('0', GPBWire::zigZagEncode64(0));
+ $this->assertSame('1', GPBWire::zigZagEncode64(-1));
+ $this->assertSame('2', GPBWire::zigZagEncode64(1));
+ $this->assertSame('3', GPBWire::zigZagEncode64(-2));
+ $this->assertSame(
+ '2147483646', // 0x7FFFFFE
+ GPBWire::zigZagEncode64(0x3FFFFFFF));
+ $this->assertSame(
+ '2147483647', // 0x7FFFFFF
+ GPBWire::zigZagEncode64(-1073741824)); // 0xFFFFFFFFC0000000
+ $this->assertSame(
+ '4294967294', // 0xFFFFFFFE
+ GPBWire::zigZagEncode64(2147483647)); // 0x7FFFFFFF
+ $this->assertSame(
+ '4294967295', // 0xFFFFFFFF
+ GPBWire::zigZagEncode64(-2147483648)); // 0xFFFFFFFF80000000
+ $this->assertSame(
+ '18446744073709551614', // 0xFFFFFFFFFFFFFFFE
+ // 0x7FFFFFFFFFFFFFFF
+ GPBWire::zigZagEncode64("9223372036854775807"));
+ $this->assertSame(
+ '18446744073709551615', // 0xFFFFFFFFFFFFFFFF
+ // 0x8000000000000000
+ GPBWire::zigZagEncode64("-9223372036854775808"));
+
+ $this->assertSame('0', GPBWire::zigZagDecode64(0));
+ $this->assertSame('-1', GPBWire::zigZagDecode64(1));
+ $this->assertSame('1', GPBWire::zigZagDecode64(2));
+ $this->assertSame('-2', GPBWire::zigZagDecode64(3));
+ } else {
+ $this->assertSame(0, GPBWire::zigZagEncode64(0));
+ $this->assertSame(1, GPBWire::zigZagEncode64(-1));
+ $this->assertSame(2, GPBWire::zigZagEncode64(1));
+ $this->assertSame(3, GPBWire::zigZagEncode64(-2));
+ $this->assertSame(0x7FFFFFFE, GPBWire::zigZagEncode64(0x3FFFFFFF));
+ $this->assertSame(
+ 0x7FFFFFFF,
+ GPBWire::zigZagEncode64(0xFFFFFFFFC0000000));
+ $this->assertSame(
+ 0xFFFFFFFE,
+ GPBWire::zigZagEncode64(0x7FFFFFFF));
+ $this->assertSame(
+ 0xFFFFFFFF,
+ GPBWire::zigZagEncode64(0xFFFFFFFF80000000));
+ $this->assertSame(
+ -2, // 0xFFFFFFFFFFFFFFFE
+ GPBWire::zigZagEncode64(0x7FFFFFFFFFFFFFFF));
+ $this->assertSame(
+ -1, // 0xFFFFFFFFFFFFFFFF
+ GPBWire::zigZagEncode64(0x8000000000000000));
+
+ $this->assertSame(0, GPBWire::zigZagDecode64(0));
+ $this->assertSame(-1, GPBWire::zigZagDecode64(1));
+ $this->assertSame(1, GPBWire::zigZagDecode64(2));
+ $this->assertSame(-2, GPBWire::zigZagDecode64(3));
+ }
+
+ // Round trip
+ $this->assertSame(0, GPBWire::zigZagDecode32(GPBWire::zigZagEncode32(0)));
+ $this->assertSame(1, GPBWire::zigZagDecode32(GPBWire::zigZagEncode32(1)));
+ $this->assertSame(-1, GPBWire::zigZagDecode32(GPBWire::zigZagEncode32(-1)));
+ $this->assertSame(14927,
+ GPBWire::zigZagDecode32(GPBWire::zigZagEncode32(14927)));
+ $this->assertSame(-3612,
+ GPBWire::zigZagDecode32(GPBWire::zigZagEncode32(-3612)));
+ }
+
+ public function testDecode()
+ {
+ $m = new TestMessage();
+ $m->decode(TestUtil::getGoldenTestMessage());
+ TestUtil::assertTestMessage($m);
+ }
+
+ public function testDescriptorDecode()
+ {
+ $file_desc_set = new FileDescriptorSet();
+ $file_desc_set->decode(hex2bin(
+ "0a3b0a12746573745f696e636c7564652e70726f746f120362617222180a" .
+ "0b54657374496e636c75646512090a0161180120012805620670726f746f33"));
+
+ $this->assertSame(1, sizeof($file_desc_set->getFile()));
+
+ $file_desc = $file_desc_set->getFile()[0];
+ $this->assertSame("test_include.proto", $file_desc->getName());
+ $this->assertSame("bar", $file_desc->getPackage());
+ $this->assertSame(0, sizeof($file_desc->getDependency()));
+ $this->assertSame(1, sizeof($file_desc->getMessageType()));
+ $this->assertSame(0, sizeof($file_desc->getEnumType()));
+ $this->assertSame("proto3", $file_desc->getSyntax());
+
+ $desc = $file_desc->getMessageType()[0];
+ $this->assertSame("TestInclude", $desc->getName());
+ $this->assertSame(1, sizeof($desc->getField()));
+ $this->assertSame(0, sizeof($desc->getNestedType()));
+ $this->assertSame(0, sizeof($desc->getEnumType()));
+ $this->assertSame(0, sizeof($desc->getOneofDecl()));
+
+ $field = $desc->getField()[0];
+ $this->assertSame("a", $field->getName());
+ $this->assertSame(1, $field->getNumber());
+ $this->assertSame(GPBLabel::OPTIONAL, $field->getLabel());
+ $this->assertSame(GPBType::INT32, $field->getType());
+ }
+
+ public function testReadVarint64()
+ {
+ $var = 0;
+
+ // Empty buffer.
+ $input = new InputStream(hex2bin(''));
+ $this->assertFalse($input->readVarint64($var));
+
+ // The largest varint is 10 bytes long.
+ $input = new InputStream(hex2bin('8080808080808080808001'));
+ $this->assertFalse($input->readVarint64($var));
+
+ // Corrupted varint.
+ $input = new InputStream(hex2bin('808080'));
+ $this->assertFalse($input->readVarint64($var));
+
+ // Normal case.
+ $input = new InputStream(hex2bin('808001'));
+ $this->assertTrue($input->readVarint64($var));
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('16384', $var);
+ } else {
+ $this->assertSame(16384, $var);
+ }
+ $this->assertFalse($input->readVarint64($var));
+
+ // Read two varint.
+ $input = new InputStream(hex2bin('808001808002'));
+ $this->assertTrue($input->readVarint64($var));
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('16384', $var);
+ } else {
+ $this->assertSame(16384, $var);
+ }
+ $this->assertTrue($input->readVarint64($var));
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('32768', $var);
+ } else {
+ $this->assertSame(32768, $var);
+ }
+ $this->assertFalse($input->readVarint64($var));
+ }
+
+ public function testReadVarint32()
+ {
+ $var = 0;
+
+ // Empty buffer.
+ $input = new InputStream(hex2bin(''));
+ $this->assertFalse($input->readVarint32($var));
+
+ // The largest varint is 10 bytes long.
+ $input = new InputStream(hex2bin('8080808080808080808001'));
+ $this->assertFalse($input->readVarint32($var));
+
+ // Corrupted varint.
+ $input = new InputStream(hex2bin('808080'));
+ $this->assertFalse($input->readVarint32($var));
+
+ // Normal case.
+ $input = new InputStream(hex2bin('808001'));
+ $this->assertTrue($input->readVarint32($var));
+ $this->assertSame(16384, $var);
+ $this->assertFalse($input->readVarint32($var));
+
+ // Read two varint.
+ $input = new InputStream(hex2bin('808001808002'));
+ $this->assertTrue($input->readVarint32($var));
+ $this->assertSame(16384, $var);
+ $this->assertTrue($input->readVarint32($var));
+ $this->assertSame(32768, $var);
+ $this->assertFalse($input->readVarint32($var));
+
+ // Read a 64-bit integer. High-order bits should be discarded.
+ $input = new InputStream(hex2bin('808081808001'));
+ $this->assertTrue($input->readVarint32($var));
+ $this->assertSame(16384, $var);
+ $this->assertFalse($input->readVarint32($var));
+ }
+
+ public function testReadTag()
+ {
+ $input = new InputStream(hex2bin('808001'));
+ $tag = $input->readTag();
+ $this->assertSame(16384, $tag);
+ $tag = $input->readTag();
+ $this->assertSame(0, $tag);
+ }
+
+ public function testPushPopLimit()
+ {
+ $input = new InputStream(hex2bin('808001'));
+ $old_limit = $input->pushLimit(0);
+ $tag = $input->readTag();
+ $this->assertSame(0, $tag);
+ $input->popLimit($old_limit);
+ $tag = $input->readTag();
+ $this->assertSame(16384, $tag);
+ }
+
+ public function testReadRaw()
+ {
+ $input = new InputStream(hex2bin('808001'));
+ $buffer = null;
+
+ $this->assertTrue($input->readRaw(3, $buffer));
+ $this->assertSame(hex2bin('808001'), $buffer);
+
+ $this->assertFalse($input->readRaw(1, $buffer));
+ }
+
+ public function testWriteVarint32()
+ {
+ $output = new OutputStream(3);
+ $output->writeVarint32(16384);
+ $this->assertSame(hex2bin('808001'), $output->getData());
+ }
+
+ public function testWriteVarint64()
+ {
+ $output = new OutputStream(10);
+ $output->writeVarint64(-43);
+ $this->assertSame(hex2bin('D5FFFFFFFFFFFFFFFF01'), $output->getData());
+ }
+
+ public function testWriteLittleEndian32()
+ {
+ $output = new OutputStream(4);
+ $output->writeLittleEndian32(46);
+ $this->assertSame(hex2bin('2E000000'), $output->getData());
+ }
+
+ public function testWriteLittleEndian64()
+ {
+ $output = new OutputStream(8);
+ $output->writeLittleEndian64(47);
+ $this->assertSame(hex2bin('2F00000000000000'), $output->getData());
+ }
+
+ public function testByteSize()
+ {
+ $m = new TestMessage();
+ TestUtil::setTestMessage($m);
+ $this->assertSame(447, $m->byteSize());
+ }
+
+ public function testPackedByteSize()
+ {
+ $m = new TestPackedMessage();
+ TestUtil::setTestPackedMessage($m);
+ $this->assertSame(156, $m->byteSize());
+ }
+}
diff --git a/php/tests/test.pb.php b/php/tests/test.pb.php
new file mode 100644
index 00000000..ed316b6e
--- /dev/null
+++ b/php/tests/test.pb.php
@@ -0,0 +1,1385 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: test.proto
+
+namespace Foo;
+
+require_once('test_include.pb.php');
+use Google\Protobuf\Internal\DescriptorPool;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+class TestMessage extends \Google\Protobuf\Internal\Message
+{
+ private $optional_int32 = 0;
+ private $optional_int64 = 0;
+ private $optional_uint32 = 0;
+ private $optional_uint64 = 0;
+ private $optional_sint32 = 0;
+ private $optional_sint64 = 0;
+ private $optional_fixed32 = 0;
+ private $optional_fixed64 = 0;
+ private $optional_sfixed32 = 0;
+ private $optional_sfixed64 = 0;
+ private $optional_float = 0.0;
+ private $optional_double = 0.0;
+ private $optional_bool = false;
+ private $optional_string = '';
+ private $optional_bytes = '';
+ private $optional_enum = 0;
+ private $optional_message = null;
+ private $optional_included_message = null;
+ private $recursive = null;
+ private $repeated_int32;
+ private $repeated_int64;
+ private $repeated_uint32;
+ private $repeated_uint64;
+ private $repeated_sint32;
+ private $repeated_sint64;
+ private $repeated_fixed32;
+ private $repeated_fixed64;
+ private $repeated_sfixed32;
+ private $repeated_sfixed64;
+ private $repeated_float;
+ private $repeated_double;
+ private $repeated_bool;
+ private $repeated_string;
+ private $repeated_bytes;
+ private $repeated_enum;
+ private $repeated_message;
+ private $repeated_recursive;
+ private $map_int32_int32;
+ private $map_int64_int64;
+ private $map_uint32_uint32;
+ private $map_uint64_uint64;
+ private $map_sint32_sint32;
+ private $map_sint64_sint64;
+ private $map_fixed32_fixed32;
+ private $map_fixed64_fixed64;
+ private $map_sfixed32_sfixed32;
+ private $map_sfixed64_sfixed64;
+ private $map_int32_float;
+ private $map_int32_double;
+ private $map_bool_bool;
+ private $map_string_string;
+ private $map_int32_bytes;
+ private $map_int32_enum;
+ private $map_int32_message;
+ private $map_recursive;
+ protected $my_oneof;
+
+ public function getOptionalInt32()
+ {
+ return $this->optional_int32;
+ }
+
+ public function setOptionalInt32($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->optional_int32 = $var;
+ }
+
+ public function getOptionalInt64()
+ {
+ return $this->optional_int64;
+ }
+
+ public function setOptionalInt64($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->optional_int64 = $var;
+ }
+
+ public function getOptionalUint32()
+ {
+ return $this->optional_uint32;
+ }
+
+ public function setOptionalUint32($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->optional_uint32 = $var;
+ }
+
+ public function getOptionalUint64()
+ {
+ return $this->optional_uint64;
+ }
+
+ public function setOptionalUint64($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->optional_uint64 = $var;
+ }
+
+ public function getOptionalSint32()
+ {
+ return $this->optional_sint32;
+ }
+
+ public function setOptionalSint32($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->optional_sint32 = $var;
+ }
+
+ public function getOptionalSint64()
+ {
+ return $this->optional_sint64;
+ }
+
+ public function setOptionalSint64($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->optional_sint64 = $var;
+ }
+
+ public function getOptionalFixed32()
+ {
+ return $this->optional_fixed32;
+ }
+
+ public function setOptionalFixed32($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->optional_fixed32 = $var;
+ }
+
+ public function getOptionalFixed64()
+ {
+ return $this->optional_fixed64;
+ }
+
+ public function setOptionalFixed64($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->optional_fixed64 = $var;
+ }
+
+ public function getOptionalSfixed32()
+ {
+ return $this->optional_sfixed32;
+ }
+
+ public function setOptionalSfixed32($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->optional_sfixed32 = $var;
+ }
+
+ public function getOptionalSfixed64()
+ {
+ return $this->optional_sfixed64;
+ }
+
+ public function setOptionalSfixed64($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->optional_sfixed64 = $var;
+ }
+
+ public function getOptionalFloat()
+ {
+ return $this->optional_float;
+ }
+
+ public function setOptionalFloat($var)
+ {
+ GPBUtil::checkFloat($var);
+ $this->optional_float = $var;
+ }
+
+ public function getOptionalDouble()
+ {
+ return $this->optional_double;
+ }
+
+ public function setOptionalDouble($var)
+ {
+ GPBUtil::checkDouble($var);
+ $this->optional_double = $var;
+ }
+
+ public function getOptionalBool()
+ {
+ return $this->optional_bool;
+ }
+
+ public function setOptionalBool($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->optional_bool = $var;
+ }
+
+ public function getOptionalString()
+ {
+ return $this->optional_string;
+ }
+
+ public function setOptionalString($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->optional_string = $var;
+ }
+
+ public function getOptionalBytes()
+ {
+ return $this->optional_bytes;
+ }
+
+ public function setOptionalBytes($var)
+ {
+ GPBUtil::checkString($var, False);
+ $this->optional_bytes = $var;
+ }
+
+ public function getOptionalEnum()
+ {
+ return $this->optional_enum;
+ }
+
+ public function setOptionalEnum($var)
+ {
+ GPBUtil::checkEnum($var, \Foo\TestEnum::class);
+ $this->optional_enum = $var;
+ }
+
+ public function getOptionalMessage()
+ {
+ return $this->optional_message;
+ }
+
+ public function setOptionalMessage(&$var)
+ {
+ GPBUtil::checkMessage($var, \Foo\TestMessage_Sub::class);
+ $this->optional_message = $var;
+ }
+
+ public function getOptionalIncludedMessage()
+ {
+ return $this->optional_included_message;
+ }
+
+ public function setOptionalIncludedMessage(&$var)
+ {
+ GPBUtil::checkMessage($var, \Bar\TestInclude::class);
+ $this->optional_included_message = $var;
+ }
+
+ public function getRecursive()
+ {
+ return $this->recursive;
+ }
+
+ public function setRecursive(&$var)
+ {
+ GPBUtil::checkMessage($var, \Foo\TestMessage::class);
+ $this->recursive = $var;
+ }
+
+ public function getRepeatedInt32()
+ {
+ return $this->repeated_int32;
+ }
+
+ public function setRepeatedInt32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->repeated_int32 = $var;
+ }
+
+ public function getRepeatedInt64()
+ {
+ return $this->repeated_int64;
+ }
+
+ public function setRepeatedInt64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT64);
+ $this->repeated_int64 = $var;
+ }
+
+ public function getRepeatedUint32()
+ {
+ return $this->repeated_uint32;
+ }
+
+ public function setRepeatedUint32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::UINT32);
+ $this->repeated_uint32 = $var;
+ }
+
+ public function getRepeatedUint64()
+ {
+ return $this->repeated_uint64;
+ }
+
+ public function setRepeatedUint64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::UINT64);
+ $this->repeated_uint64 = $var;
+ }
+
+ public function getRepeatedSint32()
+ {
+ return $this->repeated_sint32;
+ }
+
+ public function setRepeatedSint32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SINT32);
+ $this->repeated_sint32 = $var;
+ }
+
+ public function getRepeatedSint64()
+ {
+ return $this->repeated_sint64;
+ }
+
+ public function setRepeatedSint64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SINT64);
+ $this->repeated_sint64 = $var;
+ }
+
+ public function getRepeatedFixed32()
+ {
+ return $this->repeated_fixed32;
+ }
+
+ public function setRepeatedFixed32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FIXED32);
+ $this->repeated_fixed32 = $var;
+ }
+
+ public function getRepeatedFixed64()
+ {
+ return $this->repeated_fixed64;
+ }
+
+ public function setRepeatedFixed64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FIXED64);
+ $this->repeated_fixed64 = $var;
+ }
+
+ public function getRepeatedSfixed32()
+ {
+ return $this->repeated_sfixed32;
+ }
+
+ public function setRepeatedSfixed32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SFIXED32);
+ $this->repeated_sfixed32 = $var;
+ }
+
+ public function getRepeatedSfixed64()
+ {
+ return $this->repeated_sfixed64;
+ }
+
+ public function setRepeatedSfixed64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SFIXED64);
+ $this->repeated_sfixed64 = $var;
+ }
+
+ public function getRepeatedFloat()
+ {
+ return $this->repeated_float;
+ }
+
+ public function setRepeatedFloat(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FLOAT);
+ $this->repeated_float = $var;
+ }
+
+ public function getRepeatedDouble()
+ {
+ return $this->repeated_double;
+ }
+
+ public function setRepeatedDouble(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::DOUBLE);
+ $this->repeated_double = $var;
+ }
+
+ public function getRepeatedBool()
+ {
+ return $this->repeated_bool;
+ }
+
+ public function setRepeatedBool(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::BOOL);
+ $this->repeated_bool = $var;
+ }
+
+ public function getRepeatedString()
+ {
+ return $this->repeated_string;
+ }
+
+ public function setRepeatedString(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::STRING);
+ $this->repeated_string = $var;
+ }
+
+ public function getRepeatedBytes()
+ {
+ return $this->repeated_bytes;
+ }
+
+ public function setRepeatedBytes(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::BYTES);
+ $this->repeated_bytes = $var;
+ }
+
+ public function getRepeatedEnum()
+ {
+ return $this->repeated_enum;
+ }
+
+ public function setRepeatedEnum(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::ENUM, Foo\TestEnum::class);
+ $this->repeated_enum = $var;
+ }
+
+ public function getRepeatedMessage()
+ {
+ return $this->repeated_message;
+ }
+
+ public function setRepeatedMessage(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Foo\TestMessage_Sub::class);
+ $this->repeated_message = $var;
+ }
+
+ public function getRepeatedRecursive()
+ {
+ return $this->repeated_recursive;
+ }
+
+ public function setRepeatedRecursive(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::MESSAGE, \Foo\TestMessage::class);
+ $this->repeated_recursive = $var;
+ }
+
+ public function getOneofInt32()
+ {
+ return $this->readOneof(51);
+ }
+
+ public function setOneofInt32($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->writeOneof(51, $var);
+ }
+
+ public function getOneofInt64()
+ {
+ return $this->readOneof(52);
+ }
+
+ public function setOneofInt64($var)
+ {
+ GPBUtil::checkInt64($var);
+ $this->writeOneof(52, $var);
+ }
+
+ public function getOneofUint32()
+ {
+ return $this->readOneof(53);
+ }
+
+ public function setOneofUint32($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->writeOneof(53, $var);
+ }
+
+ public function getOneofUint64()
+ {
+ return $this->readOneof(54);
+ }
+
+ public function setOneofUint64($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->writeOneof(54, $var);
+ }
+
+ public function getOneofSint32()
+ {
+ return $this->readOneof(55);
+ }
+
+ public function setOneofSint32($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->writeOneof(55, $var);
+ }
+
+ public function getOneofSint64()
+ {
+ return $this->readOneof(56);
+ }
+
+ public function setOneofSint64($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->writeOneof(56, $var);
+ }
+
+ public function getOneofFixed32()
+ {
+ return $this->readOneof(57);
+ }
+
+ public function setOneofFixed32($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->writeOneof(57, $var);
+ }
+
+ public function getOneofFixed64()
+ {
+ return $this->readOneof(58);
+ }
+
+ public function setOneofFixed64($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->writeOneof(58, $var);
+ }
+
+ public function getOneofSfixed32()
+ {
+ return $this->readOneof(59);
+ }
+
+ public function setOneofSfixed32($var)
+ {
+ GPBUtil::checkUint32($var);
+ $this->writeOneof(59, $var);
+ }
+
+ public function getOneofSfixed64()
+ {
+ return $this->readOneof(60);
+ }
+
+ public function setOneofSfixed64($var)
+ {
+ GPBUtil::checkUint64($var);
+ $this->writeOneof(60, $var);
+ }
+
+ public function getOneofDouble()
+ {
+ return $this->readOneof(61);
+ }
+
+ public function setOneofDouble($var)
+ {
+ GPBUtil::checkDouble($var);
+ $this->writeOneof(61, $var);
+ }
+
+ public function getOneofFloat()
+ {
+ return $this->readOneof(62);
+ }
+
+ public function setOneofFloat($var)
+ {
+ GPBUtil::checkFloat($var);
+ $this->writeOneof(62, $var);
+ }
+
+ public function getOneofBool()
+ {
+ return $this->readOneof(63);
+ }
+
+ public function setOneofBool($var)
+ {
+ GPBUtil::checkBool($var);
+ $this->writeOneof(63, $var);
+ }
+
+ public function getOneofString()
+ {
+ return $this->readOneof(64);
+ }
+
+ public function setOneofString($var)
+ {
+ GPBUtil::checkString($var, True);
+ $this->writeOneof(64, $var);
+ }
+
+ public function getOneofBytes()
+ {
+ return $this->readOneof(65);
+ }
+
+ public function setOneofBytes($var)
+ {
+ GPBUtil::checkString($var, False);
+ $this->writeOneof(65, $var);
+ }
+
+ public function getOneofEnum()
+ {
+ return $this->readOneof(66);
+ }
+
+ public function setOneofEnum($var)
+ {
+ GPBUtil::checkEnum($var, \Foo\TestEnum::class);
+ $this->writeOneof(66, $var);
+ }
+
+ public function getOneofMessage()
+ {
+ return $this->readOneof(67);
+ }
+
+ public function setOneofMessage(&$var)
+ {
+ GPBUtil::checkMessage($var, \Foo\TestMessage_Sub::class);
+ $this->writeOneof(67, $var);
+ }
+
+ public function getMapInt32Int32()
+ {
+ return $this->map_int32_int32;
+ }
+
+ public function setMapInt32Int32(&$var)
+ {
+ $this->map_int32_int32 = $var;
+ }
+
+ public function getMapInt64Int64()
+ {
+ return $this->map_int64_int64;
+ }
+
+ public function setMapInt64Int64(&$var)
+ {
+ $this->map_int64_int64 = $var;
+ }
+
+ public function getMapUint32Uint32()
+ {
+ return $this->map_uint32_uint32;
+ }
+
+ public function setMapUint32Uint32(&$var)
+ {
+ $this->map_uint32_uint32 = $var;
+ }
+
+ public function getMapUint64Uint64()
+ {
+ return $this->map_uint64_uint64;
+ }
+
+ public function setMapUint64Uint64(&$var)
+ {
+ $this->map_uint64_uint64 = $var;
+ }
+
+ public function getMapSint32Sint32()
+ {
+ return $this->map_sint32_sint32;
+ }
+
+ public function setMapSint32Sint32(&$var)
+ {
+ $this->map_sint32_sint32 = $var;
+ }
+
+ public function getMapSint64Sint64()
+ {
+ return $this->map_sint64_sint64;
+ }
+
+ public function setMapSint64Sint64(&$var)
+ {
+ $this->map_sint64_sint64 = $var;
+ }
+
+ public function getMapFixed32Fixed32()
+ {
+ return $this->map_fixed32_fixed32;
+ }
+
+ public function setMapFixed32Fixed32(&$var)
+ {
+ $this->map_fixed32_fixed32 = $var;
+ }
+
+ public function getMapFixed64Fixed64()
+ {
+ return $this->map_fixed64_fixed64;
+ }
+
+ public function setMapFixed64Fixed64(&$var)
+ {
+ $this->map_fixed64_fixed64 = $var;
+ }
+
+ public function getMapSfixed32Sfixed32()
+ {
+ return $this->map_sfixed32_sfixed32;
+ }
+
+ public function setMapSfixed32Sfixed32(&$var)
+ {
+ $this->map_sfixed32_sfixed32 = $var;
+ }
+
+ public function getMapSfixed64Sfixed64()
+ {
+ return $this->map_sfixed64_sfixed64;
+ }
+
+ public function setMapSfixed64Sfixed64(&$var)
+ {
+ $this->map_sfixed64_sfixed64 = $var;
+ }
+
+ public function getMapInt32Float()
+ {
+ return $this->map_int32_float;
+ }
+
+ public function setMapInt32Float(&$var)
+ {
+ $this->map_int32_float = $var;
+ }
+
+ public function getMapInt32Double()
+ {
+ return $this->map_int32_double;
+ }
+
+ public function setMapInt32Double(&$var)
+ {
+ $this->map_int32_double = $var;
+ }
+
+ public function getMapBoolBool()
+ {
+ return $this->map_bool_bool;
+ }
+
+ public function setMapBoolBool(&$var)
+ {
+ $this->map_bool_bool = $var;
+ }
+
+ public function getMapStringString()
+ {
+ return $this->map_string_string;
+ }
+
+ public function setMapStringString(&$var)
+ {
+ $this->map_string_string = $var;
+ }
+
+ public function getMapInt32Bytes()
+ {
+ return $this->map_int32_bytes;
+ }
+
+ public function setMapInt32Bytes(&$var)
+ {
+ $this->map_int32_bytes = $var;
+ }
+
+ public function getMapInt32Enum()
+ {
+ return $this->map_int32_enum;
+ }
+
+ public function setMapInt32Enum(&$var)
+ {
+ $this->map_int32_enum = $var;
+ }
+
+ public function getMapInt32Message()
+ {
+ return $this->map_int32_message;
+ }
+
+ public function setMapInt32Message(&$var)
+ {
+ $this->map_int32_message = $var;
+ }
+
+ public function getMapRecursive()
+ {
+ return $this->map_recursive;
+ }
+
+ public function setMapRecursive(&$var)
+ {
+ $this->map_recursive = $var;
+ }
+
+ public function getMyOneof()
+ {
+ return $this->my_oneof;
+ }
+
+}
+
+class TestMessage_Sub extends \Google\Protobuf\Internal\Message
+{
+ private $a = 0;
+
+ public function getA()
+ {
+ return $this->a;
+ }
+
+ public function setA($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->a = $var;
+ }
+
+}
+
+class TestPackedMessage extends \Google\Protobuf\Internal\Message
+{
+ private $repeated_int32;
+ private $repeated_int64;
+ private $repeated_uint32;
+ private $repeated_uint64;
+ private $repeated_sint32;
+ private $repeated_sint64;
+ private $repeated_fixed32;
+ private $repeated_fixed64;
+ private $repeated_sfixed32;
+ private $repeated_sfixed64;
+ private $repeated_float;
+ private $repeated_double;
+ private $repeated_bool;
+ private $repeated_enum;
+
+ public function getRepeatedInt32()
+ {
+ return $this->repeated_int32;
+ }
+
+ public function setRepeatedInt32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->repeated_int32 = $var;
+ }
+
+ public function getRepeatedInt64()
+ {
+ return $this->repeated_int64;
+ }
+
+ public function setRepeatedInt64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT64);
+ $this->repeated_int64 = $var;
+ }
+
+ public function getRepeatedUint32()
+ {
+ return $this->repeated_uint32;
+ }
+
+ public function setRepeatedUint32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::UINT32);
+ $this->repeated_uint32 = $var;
+ }
+
+ public function getRepeatedUint64()
+ {
+ return $this->repeated_uint64;
+ }
+
+ public function setRepeatedUint64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::UINT64);
+ $this->repeated_uint64 = $var;
+ }
+
+ public function getRepeatedSint32()
+ {
+ return $this->repeated_sint32;
+ }
+
+ public function setRepeatedSint32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SINT32);
+ $this->repeated_sint32 = $var;
+ }
+
+ public function getRepeatedSint64()
+ {
+ return $this->repeated_sint64;
+ }
+
+ public function setRepeatedSint64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SINT64);
+ $this->repeated_sint64 = $var;
+ }
+
+ public function getRepeatedFixed32()
+ {
+ return $this->repeated_fixed32;
+ }
+
+ public function setRepeatedFixed32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FIXED32);
+ $this->repeated_fixed32 = $var;
+ }
+
+ public function getRepeatedFixed64()
+ {
+ return $this->repeated_fixed64;
+ }
+
+ public function setRepeatedFixed64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FIXED64);
+ $this->repeated_fixed64 = $var;
+ }
+
+ public function getRepeatedSfixed32()
+ {
+ return $this->repeated_sfixed32;
+ }
+
+ public function setRepeatedSfixed32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SFIXED32);
+ $this->repeated_sfixed32 = $var;
+ }
+
+ public function getRepeatedSfixed64()
+ {
+ return $this->repeated_sfixed64;
+ }
+
+ public function setRepeatedSfixed64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SFIXED64);
+ $this->repeated_sfixed64 = $var;
+ }
+
+ public function getRepeatedFloat()
+ {
+ return $this->repeated_float;
+ }
+
+ public function setRepeatedFloat(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FLOAT);
+ $this->repeated_float = $var;
+ }
+
+ public function getRepeatedDouble()
+ {
+ return $this->repeated_double;
+ }
+
+ public function setRepeatedDouble(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::DOUBLE);
+ $this->repeated_double = $var;
+ }
+
+ public function getRepeatedBool()
+ {
+ return $this->repeated_bool;
+ }
+
+ public function setRepeatedBool(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::BOOL);
+ $this->repeated_bool = $var;
+ }
+
+ public function getRepeatedEnum()
+ {
+ return $this->repeated_enum;
+ }
+
+ public function setRepeatedEnum(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::ENUM, Foo\TestEnum::class);
+ $this->repeated_enum = $var;
+ }
+
+}
+
+class TestUnpackedMessage extends \Google\Protobuf\Internal\Message
+{
+ private $repeated_int32;
+ private $repeated_int64;
+ private $repeated_uint32;
+ private $repeated_uint64;
+ private $repeated_sint32;
+ private $repeated_sint64;
+ private $repeated_fixed32;
+ private $repeated_fixed64;
+ private $repeated_sfixed32;
+ private $repeated_sfixed64;
+ private $repeated_float;
+ private $repeated_double;
+ private $repeated_bool;
+ private $repeated_enum;
+
+ public function getRepeatedInt32()
+ {
+ return $this->repeated_int32;
+ }
+
+ public function setRepeatedInt32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT32);
+ $this->repeated_int32 = $var;
+ }
+
+ public function getRepeatedInt64()
+ {
+ return $this->repeated_int64;
+ }
+
+ public function setRepeatedInt64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::INT64);
+ $this->repeated_int64 = $var;
+ }
+
+ public function getRepeatedUint32()
+ {
+ return $this->repeated_uint32;
+ }
+
+ public function setRepeatedUint32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::UINT32);
+ $this->repeated_uint32 = $var;
+ }
+
+ public function getRepeatedUint64()
+ {
+ return $this->repeated_uint64;
+ }
+
+ public function setRepeatedUint64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::UINT64);
+ $this->repeated_uint64 = $var;
+ }
+
+ public function getRepeatedSint32()
+ {
+ return $this->repeated_sint32;
+ }
+
+ public function setRepeatedSint32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SINT32);
+ $this->repeated_sint32 = $var;
+ }
+
+ public function getRepeatedSint64()
+ {
+ return $this->repeated_sint64;
+ }
+
+ public function setRepeatedSint64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SINT64);
+ $this->repeated_sint64 = $var;
+ }
+
+ public function getRepeatedFixed32()
+ {
+ return $this->repeated_fixed32;
+ }
+
+ public function setRepeatedFixed32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FIXED32);
+ $this->repeated_fixed32 = $var;
+ }
+
+ public function getRepeatedFixed64()
+ {
+ return $this->repeated_fixed64;
+ }
+
+ public function setRepeatedFixed64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FIXED64);
+ $this->repeated_fixed64 = $var;
+ }
+
+ public function getRepeatedSfixed32()
+ {
+ return $this->repeated_sfixed32;
+ }
+
+ public function setRepeatedSfixed32(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SFIXED32);
+ $this->repeated_sfixed32 = $var;
+ }
+
+ public function getRepeatedSfixed64()
+ {
+ return $this->repeated_sfixed64;
+ }
+
+ public function setRepeatedSfixed64(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::SFIXED64);
+ $this->repeated_sfixed64 = $var;
+ }
+
+ public function getRepeatedFloat()
+ {
+ return $this->repeated_float;
+ }
+
+ public function setRepeatedFloat(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::FLOAT);
+ $this->repeated_float = $var;
+ }
+
+ public function getRepeatedDouble()
+ {
+ return $this->repeated_double;
+ }
+
+ public function setRepeatedDouble(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::DOUBLE);
+ $this->repeated_double = $var;
+ }
+
+ public function getRepeatedBool()
+ {
+ return $this->repeated_bool;
+ }
+
+ public function setRepeatedBool(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::BOOL);
+ $this->repeated_bool = $var;
+ }
+
+ public function getRepeatedEnum()
+ {
+ return $this->repeated_enum;
+ }
+
+ public function setRepeatedEnum(&$var)
+ {
+ GPBUtil::checkRepeatedField($var, GPBType::ENUM, Foo\TestEnum::class);
+ $this->repeated_enum = $var;
+ }
+
+}
+
+class TestEnum
+{
+ const ZERO = 0;
+ const ONE = 1;
+}
+
+$pool = DescriptorPool::getGeneratedPool();
+
+$pool->internalAddGeneratedFile(hex2bin(
+ "0a83250a0a746573742e70726f746f1203666f6f1a12746573745f696e63" .
+ "6c7564652e70726f746f22be1d0a0b546573744d65737361676512160a0e" .
+ "6f7074696f6e616c5f696e74333218012001280512160a0e6f7074696f6e" .
+ "616c5f696e74363418022001280312170a0f6f7074696f6e616c5f75696e" .
+ "74333218032001280d12170a0f6f7074696f6e616c5f75696e7436341804" .
+ "2001280412170a0f6f7074696f6e616c5f73696e74333218052001281112" .
+ "170a0f6f7074696f6e616c5f73696e74363418062001281212180a106f70" .
+ "74696f6e616c5f6669786564333218072001280712180a106f7074696f6e" .
+ "616c5f6669786564363418082001280612190a116f7074696f6e616c5f73" .
+ "6669786564333218092001280f12190a116f7074696f6e616c5f73666978" .
+ "65643634180a2001281012160a0e6f7074696f6e616c5f666c6f6174180b" .
+ "2001280212170a0f6f7074696f6e616c5f646f75626c65180c2001280112" .
+ "150a0d6f7074696f6e616c5f626f6f6c180d2001280812170a0f6f707469" .
+ "6f6e616c5f737472696e67180e2001280912160a0e6f7074696f6e616c5f" .
+ "6279746573180f2001280c12240a0d6f7074696f6e616c5f656e756d1810" .
+ "2001280e320d2e666f6f2e54657374456e756d122e0a106f7074696f6e61" .
+ "6c5f6d65737361676518112001280b32142e666f6f2e546573744d657373" .
+ "6167652e53756212330a196f7074696f6e616c5f696e636c756465645f6d" .
+ "65737361676518122001280b32102e6261722e54657374496e636c756465" .
+ "12230a0972656375727369766518132001280b32102e666f6f2e54657374" .
+ "4d65737361676512160a0e72657065617465645f696e743332181f200328" .
+ "0512160a0e72657065617465645f696e74363418202003280312170a0f72" .
+ "657065617465645f75696e74333218212003280d12170a0f726570656174" .
+ "65645f75696e74363418222003280412170a0f72657065617465645f7369" .
+ "6e74333218232003281112170a0f72657065617465645f73696e74363418" .
+ "242003281212180a1072657065617465645f666978656433321825200328" .
+ "0712180a1072657065617465645f6669786564363418262003280612190a" .
+ "1172657065617465645f736669786564333218272003280f12190a117265" .
+ "7065617465645f736669786564363418282003281012160a0e7265706561" .
+ "7465645f666c6f617418292003280212170a0f72657065617465645f646f" .
+ "75626c65182a2003280112150a0d72657065617465645f626f6f6c182b20" .
+ "03280812170a0f72657065617465645f737472696e67182c200328091216" .
+ "0a0e72657065617465645f6279746573182d2003280c12240a0d72657065" .
+ "617465645f656e756d182e2003280e320d2e666f6f2e54657374456e756d" .
+ "122e0a1072657065617465645f6d657373616765182f2003280b32142e66" .
+ "6f6f2e546573744d6573736167652e537562122c0a127265706561746564" .
+ "5f72656375727369766518302003280b32102e666f6f2e546573744d6573" .
+ "7361676512150a0b6f6e656f665f696e743332183320012805480012150a" .
+ "0b6f6e656f665f696e743634183420012803480012160a0c6f6e656f665f" .
+ "75696e74333218352001280d480012160a0c6f6e656f665f75696e743634" .
+ "183620012804480012160a0c6f6e656f665f73696e74333218372001280d" .
+ "480012160a0c6f6e656f665f73696e743634183820012804480012170a0d" .
+ "6f6e656f665f6669786564333218392001280d480012170a0d6f6e656f66" .
+ "5f66697865643634183a20012804480012180a0e6f6e656f665f73666978" .
+ "65643332183b2001280d480012180a0e6f6e656f665f7366697865643634" .
+ "183c20012804480012160a0c6f6e656f665f646f75626c65183d20012801" .
+ "480012150a0b6f6e656f665f666c6f6174183e20012802480012140a0a6f" .
+ "6e656f665f626f6f6c183f20012808480012160a0c6f6e656f665f737472" .
+ "696e67184020012809480012150a0b6f6e656f665f627974657318412001" .
+ "280c480012230a0a6f6e656f665f656e756d18422001280e320d2e666f6f" .
+ "2e54657374456e756d4800122d0a0d6f6e656f665f6d6573736167651843" .
+ "2001280b32142e666f6f2e546573744d6573736167652e5375624800123c" .
+ "0a0f6d61705f696e7433325f696e74333218472003280b32232e666f6f2e" .
+ "546573744d6573736167652e4d6170496e743332496e743332456e747279" .
+ "123c0a0f6d61705f696e7436345f696e74363418482003280b32232e666f" .
+ "6f2e546573744d6573736167652e4d6170496e743634496e743634456e74" .
+ "727912400a116d61705f75696e7433325f75696e74333218492003280b32" .
+ "252e666f6f2e546573744d6573736167652e4d617055696e74333255696e" .
+ "743332456e74727912400a116d61705f75696e7436345f75696e74363418" .
+ "4a2003280b32252e666f6f2e546573744d6573736167652e4d617055696e" .
+ "74363455696e743634456e74727912400a116d61705f73696e7433325f73" .
+ "696e743332184b2003280b32252e666f6f2e546573744d6573736167652e" .
+ "4d617053696e74333253696e743332456e74727912400a116d61705f7369" .
+ "6e7436345f73696e743634184c2003280b32252e666f6f2e546573744d65" .
+ "73736167652e4d617053696e74363453696e743634456e74727912440a13" .
+ "6d61705f666978656433325f66697865643332184d2003280b32272e666f" .
+ "6f2e546573744d6573736167652e4d617046697865643332466978656433" .
+ "32456e74727912440a136d61705f666978656436345f6669786564363418" .
+ "4e2003280b32272e666f6f2e546573744d6573736167652e4d6170466978" .
+ "6564363446697865643634456e74727912480a156d61705f736669786564" .
+ "33325f7366697865643332184f2003280b32292e666f6f2e546573744d65" .
+ "73736167652e4d617053666978656433325366697865643332456e747279" .
+ "12480a156d61705f73666978656436345f73666978656436341850200328" .
+ "0b32292e666f6f2e546573744d6573736167652e4d617053666978656436" .
+ "345366697865643634456e747279123c0a0f6d61705f696e7433325f666c" .
+ "6f617418512003280b32232e666f6f2e546573744d6573736167652e4d61" .
+ "70496e743332466c6f6174456e747279123e0a106d61705f696e7433325f" .
+ "646f75626c6518522003280b32242e666f6f2e546573744d657373616765" .
+ "2e4d6170496e743332446f75626c65456e74727912380a0d6d61705f626f" .
+ "6f6c5f626f6f6c18532003280b32212e666f6f2e546573744d6573736167" .
+ "652e4d6170426f6f6c426f6f6c456e74727912400a116d61705f73747269" .
+ "6e675f737472696e6718542003280b32252e666f6f2e546573744d657373" .
+ "6167652e4d6170537472696e67537472696e67456e747279123c0a0f6d61" .
+ "705f696e7433325f627974657318552003280b32232e666f6f2e54657374" .
+ "4d6573736167652e4d6170496e7433324279746573456e747279123a0a0e" .
+ "6d61705f696e7433325f656e756d18562003280b32222e666f6f2e546573" .
+ "744d6573736167652e4d6170496e743332456e756d456e74727912400a11" .
+ "6d61705f696e7433325f6d65737361676518572003280b32252e666f6f2e" .
+ "546573744d6573736167652e4d6170496e7433324d657373616765456e74" .
+ "727912390a0d6d61705f72656375727369766518582003280b32222e666f" .
+ "6f2e546573744d6573736167652e4d6170526563757273697665456e7472" .
+ "791a340a124d6170496e743332496e743332456e747279120b0a036b6579" .
+ "180120012805120d0a0576616c75651802200128053a0238011a340a124d" .
+ "6170496e743634496e743634456e747279120b0a036b6579180120012803" .
+ "120d0a0576616c75651802200128033a0238011a360a144d617055696e74" .
+ "333255696e743332456e747279120b0a036b657918012001280d120d0a05" .
+ "76616c756518022001280d3a0238011a360a144d617055696e7436345569" .
+ "6e743634456e747279120b0a036b6579180120012804120d0a0576616c75" .
+ "651802200128043a0238011a360a144d617053696e74333253696e743332" .
+ "456e747279120b0a036b6579180120012811120d0a0576616c7565180220" .
+ "0128113a0238011a360a144d617053696e74363453696e743634456e7472" .
+ "79120b0a036b6579180120012812120d0a0576616c75651802200128123a" .
+ "0238011a380a164d61704669786564333246697865643332456e74727912" .
+ "0b0a036b6579180120012807120d0a0576616c75651802200128073a0238" .
+ "011a380a164d61704669786564363446697865643634456e747279120b0a" .
+ "036b6579180120012806120d0a0576616c75651802200128063a0238011a" .
+ "3a0a184d617053666978656433325366697865643332456e747279120b0a" .
+ "036b657918012001280f120d0a0576616c756518022001280f3a0238011a" .
+ "3a0a184d617053666978656436345366697865643634456e747279120b0a" .
+ "036b6579180120012810120d0a0576616c75651802200128103a0238011a" .
+ "340a124d6170496e743332466c6f6174456e747279120b0a036b65791801" .
+ "20012805120d0a0576616c75651802200128023a0238011a350a134d6170" .
+ "496e743332446f75626c65456e747279120b0a036b657918012001280512" .
+ "0d0a0576616c75651802200128013a0238011a320a104d6170426f6f6c42" .
+ "6f6f6c456e747279120b0a036b6579180120012808120d0a0576616c7565" .
+ "1802200128083a0238011a360a144d6170537472696e67537472696e6745" .
+ "6e747279120b0a036b6579180120012809120d0a0576616c756518022001" .
+ "28093a0238011a340a124d6170496e7433324279746573456e747279120b" .
+ "0a036b6579180120012805120d0a0576616c756518022001280c3a023801" .
+ "1a420a114d6170496e743332456e756d456e747279120b0a036b65791801" .
+ "20012805121c0a0576616c756518022001280e320d2e666f6f2e54657374" .
+ "456e756d3a0238011a4c0a144d6170496e7433324d657373616765456e74" .
+ "7279120b0a036b657918012001280512230a0576616c756518022001280b" .
+ "32142e666f6f2e546573744d6573736167652e5375623a0238011a450a11" .
+ "4d6170526563757273697665456e747279120b0a036b6579180120012805" .
+ "121f0a0576616c756518022001280b32102e666f6f2e546573744d657373" .
+ "6167653a0238011a100a0353756212090a0161180120012805420a0a086d" .
+ "795f6f6e656f6622b7030a11546573745061636b65644d65737361676512" .
+ "1a0a0e72657065617465645f696e743332185a2003280542021001121a0a" .
+ "0e72657065617465645f696e743634185b2003280342021001121b0a0f72" .
+ "657065617465645f75696e743332185c2003280d42021001121b0a0f7265" .
+ "7065617465645f75696e743634185d2003280442021001121b0a0f726570" .
+ "65617465645f73696e743332185e2003281142021001121b0a0f72657065" .
+ "617465645f73696e743634185f2003281242021001121c0a107265706561" .
+ "7465645f6669786564333218602003280742021001121c0a107265706561" .
+ "7465645f6669786564363418612003280642021001121d0a117265706561" .
+ "7465645f736669786564333218622003280f42021001121d0a1172657065" .
+ "617465645f736669786564363418632003281042021001121a0a0e726570" .
+ "65617465645f666c6f617418642003280242021001121b0a0f7265706561" .
+ "7465645f646f75626c651865200328014202100112190a0d726570656174" .
+ "65645f626f6f6c1866200328084202100112280a0d72657065617465645f" .
+ "656e756d18672003280e320d2e666f6f2e54657374456e756d4202100122" .
+ "b9030a1354657374556e7061636b65644d657373616765121a0a0e726570" .
+ "65617465645f696e743332185a2003280542021000121a0a0e7265706561" .
+ "7465645f696e743634185b2003280342021000121b0a0f72657065617465" .
+ "645f75696e743332185c2003280d42021000121b0a0f7265706561746564" .
+ "5f75696e743634185d2003280442021000121b0a0f72657065617465645f" .
+ "73696e743332185e2003281142021000121b0a0f72657065617465645f73" .
+ "696e743634185f2003281242021000121c0a1072657065617465645f6669" .
+ "786564333218602003280742021000121c0a1072657065617465645f6669" .
+ "786564363418612003280642021000121d0a1172657065617465645f7366" .
+ "69786564333218622003280f42021000121d0a1172657065617465645f73" .
+ "6669786564363418632003281042021000121a0a0e72657065617465645f" .
+ "666c6f617418642003280242021000121b0a0f72657065617465645f646f" .
+ "75626c651865200328014202100012190a0d72657065617465645f626f6f" .
+ "6c1866200328084202100012280a0d72657065617465645f656e756d1867" .
+ "2003280e320d2e666f6f2e54657374456e756d420210002a1d0a08546573" .
+ "74456e756d12080a045a45524f100012070a034f4e451001620670726f74" .
+ "6f33"
+));
+
diff --git a/php/tests/test.proto b/php/tests/test.proto
new file mode 100644
index 00000000..15709c83
--- /dev/null
+++ b/php/tests/test.proto
@@ -0,0 +1,136 @@
+syntax = "proto3";
+
+import 'test_include.proto';
+
+package foo;
+
+message TestMessage {
+ // Singular
+ int32 optional_int32 = 1;
+ int64 optional_int64 = 2;
+ uint32 optional_uint32 = 3;
+ uint64 optional_uint64 = 4;
+ sint32 optional_sint32 = 5;
+ sint64 optional_sint64 = 6;
+ fixed32 optional_fixed32 = 7;
+ fixed64 optional_fixed64 = 8;
+ sfixed32 optional_sfixed32 = 9;
+ sfixed64 optional_sfixed64 = 10;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
+
+ TestEnum optional_enum = 16;
+ Sub optional_message = 17;
+ bar.TestInclude optional_included_message = 18;
+ TestMessage recursive = 19;
+
+ // 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 TestEnum repeated_enum = 46;
+ repeated Sub repeated_message = 47;
+ repeated TestMessage repeated_recursive = 48;
+
+ oneof my_oneof {
+ int32 oneof_int32 = 51;
+ int64 oneof_int64 = 52;
+ uint32 oneof_uint32 = 53;
+ uint64 oneof_uint64 = 54;
+ uint32 oneof_sint32 = 55;
+ uint64 oneof_sint64 = 56;
+ uint32 oneof_fixed32 = 57;
+ uint64 oneof_fixed64 = 58;
+ uint32 oneof_sfixed32 = 59;
+ uint64 oneof_sfixed64 = 60;
+ double oneof_double = 61;
+ float oneof_float = 62;
+ bool oneof_bool = 63;
+ string oneof_string = 64;
+ bytes oneof_bytes = 65;
+ TestEnum oneof_enum = 66;
+ Sub oneof_message = 67;
+ }
+
+ map<int32, int32> map_int32_int32 = 71;
+ map<int64, int64> map_int64_int64 = 72;
+ map<uint32, uint32> map_uint32_uint32 = 73;
+ map<uint64, uint64> map_uint64_uint64 = 74;
+ map<sint32, sint32> map_sint32_sint32 = 75;
+ map<sint64, sint64> map_sint64_sint64 = 76;
+ map<fixed32, fixed32> map_fixed32_fixed32 = 77;
+ map<fixed64, fixed64> map_fixed64_fixed64 = 78;
+ map<sfixed32, sfixed32> map_sfixed32_sfixed32 = 79;
+ map<sfixed64, sfixed64> map_sfixed64_sfixed64 = 80;
+ map<int32, float> map_int32_float = 81;
+ map<int32, double> map_int32_double = 82;
+ map<bool, bool> map_bool_bool = 83;
+ map<string, string> map_string_string = 84;
+ map<int32, bytes> map_int32_bytes = 85;
+ map<int32, TestEnum> map_int32_enum = 86;
+ map<int32, Sub> map_int32_message = 87;
+
+ map<int32, TestMessage> map_recursive = 88;
+
+ message Sub {
+ int32 a = 1;
+ }
+
+ // NestedMessage nested_message = 90;
+}
+
+enum TestEnum {
+ ZERO = 0;
+ ONE = 1;
+}
+
+message TestPackedMessage {
+ repeated int32 repeated_int32 = 90 [packed = true];
+ repeated int64 repeated_int64 = 91 [packed = true];
+ repeated uint32 repeated_uint32 = 92 [packed = true];
+ repeated uint64 repeated_uint64 = 93 [packed = true];
+ repeated sint32 repeated_sint32 = 94 [packed = true];
+ repeated sint64 repeated_sint64 = 95 [packed = true];
+ repeated fixed32 repeated_fixed32 = 96 [packed = true];
+ repeated fixed64 repeated_fixed64 = 97 [packed = true];
+ repeated sfixed32 repeated_sfixed32 = 98 [packed = true];
+ repeated sfixed64 repeated_sfixed64 = 99 [packed = true];
+ repeated float repeated_float = 100 [packed = true];
+ repeated double repeated_double = 101 [packed = true];
+ repeated bool repeated_bool = 102 [packed = true];
+ repeated TestEnum repeated_enum = 103 [packed = true];
+}
+
+// Need to be in sync with TestPackedMessage.
+message TestUnpackedMessage {
+ repeated int32 repeated_int32 = 90 [packed = false];
+ repeated int64 repeated_int64 = 91 [packed = false];
+ repeated uint32 repeated_uint32 = 92 [packed = false];
+ repeated uint64 repeated_uint64 = 93 [packed = false];
+ repeated sint32 repeated_sint32 = 94 [packed = false];
+ repeated sint64 repeated_sint64 = 95 [packed = false];
+ repeated fixed32 repeated_fixed32 = 96 [packed = false];
+ repeated fixed64 repeated_fixed64 = 97 [packed = false];
+ repeated sfixed32 repeated_sfixed32 = 98 [packed = false];
+ repeated sfixed64 repeated_sfixed64 = 99 [packed = false];
+ repeated float repeated_float = 100 [packed = false];
+ repeated double repeated_double = 101 [packed = false];
+ repeated bool repeated_bool = 102 [packed = false];
+ repeated TestEnum repeated_enum = 103 [packed = false];
+}
diff --git a/php/tests/test.sh b/php/tests/test.sh
new file mode 100755
index 00000000..fe3dc7f6
--- /dev/null
+++ b/php/tests/test.sh
@@ -0,0 +1,28 @@
+#!/bin/bash
+
+# Generate test file
+../../src/protoc --php_out=. test.proto test_include.proto
+
+# Compile c extension
+pushd ../ext/google/protobuf/
+make clean
+set -e
+# Add following in configure for debug: --enable-debug CFLAGS='-g -O0'
+phpize && ./configure && make
+popd
+
+tests=( array_test.php encode_decode_test.php generated_class_test.php map_field_test.php )
+
+for t in "${tests[@]}"
+do
+ echo "****************************"
+ echo "* $t"
+ echo "****************************"
+ php -dextension=../ext/google/protobuf/modules/protobuf.so `which phpunit` $t
+ echo ""
+done
+
+# Make sure to run the memory test in debug mode.
+php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
+
+USE_ZEND_ALLOC=0 valgrind --leak-check=yes php -dextension=../ext/google/protobuf/modules/protobuf.so memory_leak_test.php
diff --git a/php/tests/test_base.php b/php/tests/test_base.php
new file mode 100644
index 00000000..d461f0f7
--- /dev/null
+++ b/php/tests/test_base.php
@@ -0,0 +1,106 @@
+<?php
+
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+
+class TestBase extends PHPUnit_Framework_TestCase
+{
+
+ public function setFields(TestMessage $m)
+ {
+ TestUtil::setTestMessage($m);
+ }
+
+ public function expectFields(TestMessage $m)
+ {
+ $this->assertSame(-44, $m->getOptionalSint32());
+ $this->assertSame(46, $m->getOptionalFixed32());
+ $this->assertSame(-46, $m->getOptionalSfixed32());
+ $this->assertSame(1.5, $m->getOptionalFloat());
+ $this->assertSame(1.6, $m->getOptionalDouble());
+ $this->assertSame(true, $m->getOptionalBool());
+ $this->assertSame('a', $m->getOptionalString());
+ $this->assertSame('b', $m->getOptionalBytes());
+ $this->assertSame(33, $m->getOptionalMessage()->getA());
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame('-43', $m->getOptionalInt64());
+ $this->assertSame('43', $m->getOptionalUint64());
+ $this->assertSame('-45', $m->getOptionalSint64());
+ $this->assertSame('47', $m->getOptionalFixed64());
+ $this->assertSame('-47', $m->getOptionalSfixed64());
+ } else {
+ $this->assertSame(-43, $m->getOptionalInt64());
+ $this->assertSame(43, $m->getOptionalUint64());
+ $this->assertSame(-45, $m->getOptionalSint64());
+ $this->assertSame(47, $m->getOptionalFixed64());
+ $this->assertSame(-47, $m->getOptionalSfixed64());
+ }
+
+ $this->assertEquals(-42, $m->getRepeatedInt32()[0]);
+ $this->assertEquals(42, $m->getRepeatedUint32()[0]);
+ $this->assertEquals(-43, $m->getRepeatedInt64()[0]);
+ $this->assertEquals(43, $m->getRepeatedUint64()[0]);
+ $this->assertEquals(-44, $m->getRepeatedSint32()[0]);
+ $this->assertEquals(-45, $m->getRepeatedSint64()[0]);
+ $this->assertEquals(46, $m->getRepeatedFixed32()[0]);
+ $this->assertEquals(47, $m->getRepeatedFixed64()[0]);
+ $this->assertEquals(-46, $m->getRepeatedSfixed32()[0]);
+ $this->assertEquals(-47, $m->getRepeatedSfixed64()[0]);
+ $this->assertEquals(1.5, $m->getRepeatedFloat()[0]);
+ $this->assertEquals(1.6, $m->getRepeatedDouble()[0]);
+ $this->assertEquals(true, $m->getRepeatedBool()[0]);
+ $this->assertEquals('a', $m->getRepeatedString()[0]);
+ $this->assertEquals('b', $m->getRepeatedBytes()[0]);
+ $this->assertEquals(34, $m->getRepeatedMessage()[0]->GetA());
+
+ $this->assertEquals(-52, $m->getRepeatedInt32()[1]);
+ $this->assertEquals(52, $m->getRepeatedUint32()[1]);
+ $this->assertEquals(-53, $m->getRepeatedInt64()[1]);
+ $this->assertEquals(53, $m->getRepeatedUint64()[1]);
+ $this->assertEquals(-54, $m->getRepeatedSint32()[1]);
+ $this->assertEquals(-55, $m->getRepeatedSint64()[1]);
+ $this->assertEquals(56, $m->getRepeatedFixed32()[1]);
+ $this->assertEquals(57, $m->getRepeatedFixed64()[1]);
+ $this->assertEquals(-56, $m->getRepeatedSfixed32()[1]);
+ $this->assertEquals(-57, $m->getRepeatedSfixed64()[1]);
+ $this->assertEquals(2.5, $m->getRepeatedFloat()[1]);
+ $this->assertEquals(2.6, $m->getRepeatedDouble()[1]);
+ $this->assertEquals(false, $m->getRepeatedBool()[1]);
+ $this->assertEquals('c', $m->getRepeatedString()[1]);
+ $this->assertEquals('d', $m->getRepeatedBytes()[1]);
+ $this->assertEquals(35, $m->getRepeatedMessage()[1]->GetA());
+ }
+
+ public function expectEmptyFields(TestMessage $m)
+ {
+ $this->assertSame(0, $m->getOptionalInt32());
+ $this->assertSame(0, $m->getOptionalUint32());
+ $this->assertSame(0, $m->getOptionalSint32());
+ $this->assertSame(0, $m->getOptionalFixed32());
+ $this->assertSame(0, $m->getOptionalSfixed32());
+ $this->assertSame(0.0, $m->getOptionalFloat());
+ $this->assertSame(0.0, $m->getOptionalDouble());
+ $this->assertSame(false, $m->getOptionalBool());
+ $this->assertSame('', $m->getOptionalString());
+ $this->assertSame('', $m->getOptionalBytes());
+ $this->assertNull($m->getOptionalMessage());
+ if (PHP_INT_SIZE == 4) {
+ $this->assertSame("0", $m->getOptionalInt64());
+ $this->assertSame("0", $m->getOptionalUint64());
+ $this->assertSame("0", $m->getOptionalSint64());
+ $this->assertSame("0", $m->getOptionalFixed64());
+ $this->assertSame("0", $m->getOptionalSfixed64());
+ } else {
+ $this->assertSame(0, $m->getOptionalInt64());
+ $this->assertSame(0, $m->getOptionalUint64());
+ $this->assertSame(0, $m->getOptionalSint64());
+ $this->assertSame(0, $m->getOptionalFixed64());
+ $this->assertSame(0, $m->getOptionalSfixed64());
+ }
+ }
+
+ // This test is to avoid the warning of no test by php unit.
+ public function testNone()
+ {
+ }
+}
diff --git a/php/tests/test_include.pb.php b/php/tests/test_include.pb.php
new file mode 100644
index 00000000..2c43cc41
--- /dev/null
+++ b/php/tests/test_include.pb.php
@@ -0,0 +1,36 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: test_include.proto
+
+namespace Bar;
+
+use Google\Protobuf\Internal\DescriptorPool;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+class TestInclude extends \Google\Protobuf\Internal\Message
+{
+ private $a = 0;
+
+ public function getA()
+ {
+ return $this->a;
+ }
+
+ public function setA($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->a = $var;
+ }
+
+}
+
+$pool = DescriptorPool::getGeneratedPool();
+
+$pool->internalAddGeneratedFile(hex2bin(
+ "0a3b0a12746573745f696e636c7564652e70726f746f120362617222180a" .
+ "0b54657374496e636c75646512090a0161180120012805620670726f746f" .
+ "33"
+));
+
diff --git a/php/tests/test_include.proto b/php/tests/test_include.proto
new file mode 100644
index 00000000..9844617f
--- /dev/null
+++ b/php/tests/test_include.proto
@@ -0,0 +1,7 @@
+syntax = "proto3";
+
+package bar;
+
+message TestInclude {
+ int32 a = 1;
+}
diff --git a/php/tests/test_no_namespace.pb.php b/php/tests/test_no_namespace.pb.php
new file mode 100644
index 00000000..2f92c955
--- /dev/null
+++ b/php/tests/test_no_namespace.pb.php
@@ -0,0 +1,34 @@
+<?php
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: test_no_namespace.proto
+
+use Google\Protobuf\Internal\DescriptorPool;
+use Google\Protobuf\Internal\GPBType;
+use Google\Protobuf\Internal\RepeatedField;
+use Google\Protobuf\Internal\GPBUtil;
+
+class NoNameSpace extends \Google\Protobuf\Internal\Message
+{
+ private $a = 0;
+
+ public function getA()
+ {
+ return $this->a;
+ }
+
+ public function setA($var)
+ {
+ GPBUtil::checkInt32($var);
+ $this->a = $var;
+ }
+
+}
+
+$pool = DescriptorPool::getGeneratedPool();
+
+$pool->internalAddGeneratedFile(hex2bin(
+ "0a3b0a17746573745f6e6f5f6e616d6573706163652e70726f746f22180a" .
+ "0b4e6f4e616d65537061636512090a0161180120012805620670726f746f" .
+ "33"
+));
+
diff --git a/php/tests/test_no_namespace.proto b/php/tests/test_no_namespace.proto
new file mode 100644
index 00000000..4331aeab
--- /dev/null
+++ b/php/tests/test_no_namespace.proto
@@ -0,0 +1,5 @@
+syntax = "proto3";
+
+message NoNameSpace {
+ int32 a = 1;
+}
diff --git a/php/tests/test_util.php b/php/tests/test_util.php
new file mode 100644
index 00000000..7f2aae15
--- /dev/null
+++ b/php/tests/test_util.php
@@ -0,0 +1,440 @@
+<?php
+
+use Foo\TestEnum;
+use Foo\TestMessage;
+use Foo\TestMessage_Sub;
+use Foo\TestPackedMessage;
+use Foo\TestUnpackedMessage;
+
+define('MAX_FLOAT_DIFF', 0.000001);
+
+if (PHP_INT_SIZE == 8) {
+ define('MAX_INT_STRING', '9223372036854775807');
+ define('MAX_INT_UPPER_STRING', '9223372036854775808');
+} else {
+ define('MAX_INT_STRING', '2147483647');
+ define('MAX_INT_UPPER_STRING', '2147483648');
+}
+
+define('MAX_INT32', 2147483647);
+define('MAX_INT32_FLOAT', 2147483647.0);
+define('MAX_INT32_STRING', '2147483647');
+
+define('MIN_INT32', (int)-2147483648);
+define('MIN_INT32_FLOAT', -2147483648.0);
+define('MIN_INT32_STRING', '-2147483648');
+
+define('MAX_UINT32', 4294967295);
+define('MAX_UINT32_FLOAT', 4294967295.0);
+define('MAX_UINT32_STRING', '4294967295');
+
+define('MIN_UINT32', (int)-2147483648);
+define('MIN_UINT32_FLOAT', -2147483648.0);
+define('MIN_UINT32_STRING', '-2147483648');
+
+define('MAX_INT64_STRING', '9223372036854775807');
+define('MIN_INT64_STRING', '-9223372036854775808');
+define('MAX_UINT64_STRING', '-9223372036854775808');
+
+if (PHP_INT_SIZE === 8) {
+ define('MAX_INT64', (int)9223372036854775807);
+ define('MIN_INT64', (int)-9223372036854775808);
+ define('MAX_UINT64', (int)-9223372036854775808);
+} else {
+ define('MAX_INT64', MAX_INT64_STRING);
+ define('MIN_INT64', MIN_INT64_STRING);
+ define('MAX_UINT64', MAX_UINT64_STRING);
+}
+
+class TestUtil
+{
+
+ public static function setTestMessage(TestMessage $m)
+ {
+ $sub = new TestMessage_Sub();
+
+ $m->setOptionalInt32(-42);
+ $m->setOptionalInt64(-43);
+ $m->setOptionalUint32(42);
+ $m->setOptionalUint64(43);
+ $m->setOptionalSint32(-44);
+ $m->setOptionalSint64(-45);
+ $m->setOptionalFixed32(46);
+ $m->setOptionalFixed64(47);
+ $m->setOptionalSfixed32(-46);
+ $m->setOptionalSfixed64(-47);
+ $m->setOptionalFloat(1.5);
+ $m->setOptionalDouble(1.6);
+ $m->setOptionalBool(true);
+ $m->setOptionalString('a');
+ $m->setOptionalBytes('b');
+ $m->setOptionalEnum(TestEnum::ONE);
+ $m->setOptionalMessage($sub);
+ $m->getOptionalMessage()->SetA(33);
+
+ $m->getRepeatedInt32() []= -42;
+ $m->getRepeatedInt64() []= -43;
+ $m->getRepeatedUint32() []= 42;
+ $m->getRepeatedUint64() []= 43;
+ $m->getRepeatedSint32() []= -44;
+ $m->getRepeatedSint64() []= -45;
+ $m->getRepeatedFixed32() []= 46;
+ $m->getRepeatedFixed64() []= 47;
+ $m->getRepeatedSfixed32() []= -46;
+ $m->getRepeatedSfixed64() []= -47;
+ $m->getRepeatedFloat() []= 1.5;
+ $m->getRepeatedDouble() []= 1.6;
+ $m->getRepeatedBool() []= true;
+ $m->getRepeatedString() []= 'a';
+ $m->getRepeatedBytes() []= 'b';
+ $m->getRepeatedEnum() []= TestEnum::ZERO;
+ $m->getRepeatedMessage() []= new TestMessage_Sub();
+ $m->getRepeatedMessage()[0]->setA(34);
+
+ $m->getRepeatedInt32() []= -52;
+ $m->getRepeatedInt64() []= -53;
+ $m->getRepeatedUint32() []= 52;
+ $m->getRepeatedUint64() []= 53;
+ $m->getRepeatedSint32() []= -54;
+ $m->getRepeatedSint64() []= -55;
+ $m->getRepeatedFixed32() []= 56;
+ $m->getRepeatedFixed64() []= 57;
+ $m->getRepeatedSfixed32() []= -56;
+ $m->getRepeatedSfixed64() []= -57;
+ $m->getRepeatedFloat() []= 2.5;
+ $m->getRepeatedDouble() []= 2.6;
+ $m->getRepeatedBool() []= false;
+ $m->getRepeatedString() []= 'c';
+ $m->getRepeatedBytes() []= 'd';
+ $m->getRepeatedEnum() []= TestEnum::ONE;
+ $m->getRepeatedMessage() []= new TestMessage_Sub();
+ $m->getRepeatedMessage()[1]->SetA(35);
+
+ $m->getMapInt32Int32()[-62] = -62;
+ $m->getMapInt64Int64()[-63] = -63;
+ $m->getMapUint32Uint32()[62] = 62;
+ $m->getMapUint64Uint64()[63] = 63;
+ $m->getMapSint32Sint32()[-64] = -64;
+ $m->getMapSint64Sint64()[-65] = -65;
+ $m->getMapFixed32Fixed32()[66] = 66;
+ $m->getMapFixed64Fixed64()[67] = 67;
+ $m->getMapInt32Float()[1] = 3.5;
+ $m->getMapInt32Double()[1] = 3.6;
+ $m->getMapBoolBool()[true] = true;
+ $m->getMapStringString()['e'] = 'e';
+ $m->getMapInt32Bytes()[1] = 'f';
+ $m->getMapInt32Enum()[1] = TestEnum::ONE;
+ $m->getMapInt32Message()[1] = new TestMessage_Sub();
+ $m->getMapInt32Message()[1]->SetA(36);
+ }
+
+ public static function assertTestMessage(TestMessage $m)
+ {
+ if (PHP_INT_SIZE == 4) {
+ assert('-43' === $m->getOptionalInt64());
+ assert('43' === $m->getOptionalUint64());
+ assert('-45' === $m->getOptionalSint64());
+ assert('47' === $m->getOptionalFixed64());
+ assert('-47' === $m->getOptionalSfixed64());
+ } else {
+ assert(-43 === $m->getOptionalInt64());
+ assert(43 === $m->getOptionalUint64());
+ assert(-45 === $m->getOptionalSint64());
+ assert(47 === $m->getOptionalFixed64());
+ assert(-47 === $m->getOptionalSfixed64());
+ }
+ assert(-42 === $m->getOptionalInt32());
+ assert(42 === $m->getOptionalUint32());
+ assert(-44 === $m->getOptionalSint32());
+ assert(46 === $m->getOptionalFixed32());
+ assert(-46 === $m->getOptionalSfixed32());
+ assert(1.5 === $m->getOptionalFloat());
+ assert(1.6 === $m->getOptionalDouble());
+ assert(true=== $m->getOptionalBool());
+ assert('a' === $m->getOptionalString());
+ assert('b' === $m->getOptionalBytes());
+ assert(TestEnum::ONE === $m->getOptionalEnum());
+ assert(33 === $m->getOptionalMessage()->getA());
+
+ if (PHP_INT_SIZE == 4) {
+ assert('-43' === $m->getRepeatedInt64()[0]);
+ assert('43' === $m->getRepeatedUint64()[0]);
+ assert('-45' === $m->getRepeatedSint64()[0]);
+ assert('47' === $m->getRepeatedFixed64()[0]);
+ assert('-47' === $m->getRepeatedSfixed64()[0]);
+ } else {
+ assert(-43 === $m->getRepeatedInt64()[0]);
+ assert(43 === $m->getRepeatedUint64()[0]);
+ assert(-45 === $m->getRepeatedSint64()[0]);
+ assert(47 === $m->getRepeatedFixed64()[0]);
+ assert(-47 === $m->getRepeatedSfixed64()[0]);
+ }
+ assert(-42 === $m->getRepeatedInt32()[0]);
+ assert(42 === $m->getRepeatedUint32()[0]);
+ assert(-44 === $m->getRepeatedSint32()[0]);
+ assert(46 === $m->getRepeatedFixed32()[0]);
+ assert(-46 === $m->getRepeatedSfixed32()[0]);
+ assert(1.5 === $m->getRepeatedFloat()[0]);
+ assert(1.6 === $m->getRepeatedDouble()[0]);
+ assert(true=== $m->getRepeatedBool()[0]);
+ assert('a' === $m->getRepeatedString()[0]);
+ assert('b' === $m->getRepeatedBytes()[0]);
+ assert(TestEnum::ZERO === $m->getRepeatedEnum()[0]);
+ assert(34 === $m->getRepeatedMessage()[0]->getA());
+
+ if (PHP_INT_SIZE == 4) {
+ assert('-53' === $m->getRepeatedInt64()[1]);
+ assert('53' === $m->getRepeatedUint64()[1]);
+ assert('-55' === $m->getRepeatedSint64()[1]);
+ assert('57' === $m->getRepeatedFixed64()[1]);
+ assert('-57' === $m->getRepeatedSfixed64()[1]);
+ } else {
+ assert(-53 === $m->getRepeatedInt64()[1]);
+ assert(53 === $m->getRepeatedUint64()[1]);
+ assert(-55 === $m->getRepeatedSint64()[1]);
+ assert(57 === $m->getRepeatedFixed64()[1]);
+ assert(-57 === $m->getRepeatedSfixed64()[1]);
+ }
+ assert(-52 === $m->getRepeatedInt32()[1]);
+ assert(52 === $m->getRepeatedUint32()[1]);
+ assert(-54 === $m->getRepeatedSint32()[1]);
+ assert(56 === $m->getRepeatedFixed32()[1]);
+ assert(-56 === $m->getRepeatedSfixed32()[1]);
+ assert(2.5 === $m->getRepeatedFloat()[1]);
+ assert(2.6 === $m->getRepeatedDouble()[1]);
+ assert(false === $m->getRepeatedBool()[1]);
+ assert('c' === $m->getRepeatedString()[1]);
+ assert('d' === $m->getRepeatedBytes()[1]);
+ assert(TestEnum::ONE === $m->getRepeatedEnum()[1]);
+ assert(35 === $m->getRepeatedMessage()[1]->getA());
+
+ if (PHP_INT_SIZE == 4) {
+ assert('-63' === $m->getMapInt64Int64()['-63']);
+ assert('63' === $m->getMapUint64Uint64()['63']);
+ assert('-65' === $m->getMapSint64Sint64()['-65']);
+ assert('67' === $m->getMapFixed64Fixed64()['67']);
+ } else {
+ assert(-63 === $m->getMapInt64Int64()[-63]);
+ assert(63 === $m->getMapUint64Uint64()[63]);
+ assert(-65 === $m->getMapSint64Sint64()[-65]);
+ assert(67 === $m->getMapFixed64Fixed64()[67]);
+ }
+ assert(-62 === $m->getMapInt32Int32()[-62]);
+ assert(62 === $m->getMapUint32Uint32()[62]);
+ assert(-64 === $m->getMapSint32Sint32()[-64]);
+ assert(66 === $m->getMapFixed32Fixed32()[66]);
+ assert(3.5 === $m->getMapInt32Float()[1]);
+ assert(3.6 === $m->getMapInt32Double()[1]);
+ assert(true === $m->getMapBoolBool()[true]);
+ assert('e' === $m->getMapStringString()['e']);
+ assert('f' === $m->getMapInt32Bytes()[1]);
+ assert(TestEnum::ONE === $m->getMapInt32Enum()[1]);
+ assert(36 === $m->getMapInt32Message()[1]->GetA());
+ }
+
+ public static function getGoldenTestMessage()
+ {
+ return hex2bin(
+ "08D6FFFFFF0F" .
+ "10D5FFFFFFFFFFFFFFFF01" .
+ "182A" .
+ "202B" .
+ "2857" .
+ "3059" .
+ "3D2E000000" .
+ "412F00000000000000" .
+ "4DD2FFFFFF" .
+ "51D1FFFFFFFFFFFFFF" .
+ "5D0000C03F" .
+ "619A9999999999F93F" .
+ "6801" .
+ "720161" .
+ "7A0162" .
+ "800101" .
+ "8A01020821" .
+
+ "F801D6FFFFFF0F" .
+ "F801CCFFFFFF0F" .
+ "8002D5FFFFFFFFFFFFFFFF01" .
+ "8002CBFFFFFFFFFFFFFFFF01" .
+ "88022A" .
+ "880234" .
+ "90022B" .
+ "900235" .
+ "980257" .
+ "98026B" .
+ "A00259" .
+ "A0026D" .
+ "AD022E000000" .
+ "AD0238000000" .
+ "B1022F00000000000000" .
+ "B1023900000000000000" .
+ "BD02D2FFFFFF" .
+ "BD02C8FFFFFF" .
+ "C102D1FFFFFFFFFFFFFF" .
+ "C102C7FFFFFFFFFFFFFF" .
+ "CD020000C03F" .
+ "CD0200002040" .
+ "D1029A9999999999F93F" .
+ "D102CDCCCCCCCCCC0440" .
+ "D80201" .
+ "D80200" .
+ "E2020161" .
+ "E2020163" .
+ "EA020162" .
+ "EA020164" .
+ "F00200" .
+ "F00201" .
+ "FA02020822" .
+ "FA02020823" .
+
+ "BA040C08C2FFFFFF0F10C2FFFFFF0F" .
+ "C2041608C1FFFFFFFFFFFFFFFF0110C1FFFFFFFFFFFFFFFF01" .
+ "CA0404083E103E" .
+ "D20404083F103F" .
+ "DA0404087f107F" .
+ "E20406088101108101" .
+ "EA040A0D420000001542000000" .
+ "F20412094300000000000000114300000000000000" .
+ "8A050708011500006040" .
+ "92050B080111CDCCCCCCCCCC0C40" .
+ "9A050408011001" .
+ "A205060a0165120165" .
+ "AA05050801120166" .
+ "B2050408011001" .
+ "Ba0506080112020824"
+ );
+ }
+
+ public static function setTestPackedMessage($m)
+ {
+ $m->getRepeatedInt32()[] = -42;
+ $m->getRepeatedInt32()[] = -52;
+ $m->getRepeatedInt64()[] = -43;
+ $m->getRepeatedInt64()[] = -53;
+ $m->getRepeatedUint32()[] = 42;
+ $m->getRepeatedUint32()[] = 52;
+ $m->getRepeatedUint64()[] = 43;
+ $m->getRepeatedUint64()[] = 53;
+ $m->getRepeatedSint32()[] = -44;
+ $m->getRepeatedSint32()[] = -54;
+ $m->getRepeatedSint64()[] = -45;
+ $m->getRepeatedSint64()[] = -55;
+ $m->getRepeatedFixed32()[] = 46;
+ $m->getRepeatedFixed32()[] = 56;
+ $m->getRepeatedFixed64()[] = 47;
+ $m->getRepeatedFixed64()[] = 57;
+ $m->getRepeatedSfixed32()[] = -46;
+ $m->getRepeatedSfixed32()[] = -56;
+ $m->getRepeatedSfixed64()[] = -47;
+ $m->getRepeatedSfixed64()[] = -57;
+ $m->getRepeatedFloat()[] = 1.5;
+ $m->getRepeatedFloat()[] = 2.5;
+ $m->getRepeatedDouble()[] = 1.6;
+ $m->getRepeatedDouble()[] = 2.6;
+ $m->getRepeatedBool()[] = true;
+ $m->getRepeatedBool()[] = false;
+ $m->getRepeatedEnum()[] = TestEnum::ONE;
+ $m->getRepeatedEnum()[] = TestEnum::ZERO;
+ }
+
+ public static function assertTestPackedMessage($m)
+ {
+ assert(2 === count($m->getRepeatedInt32()));
+ assert(2 === count($m->getRepeatedInt64()));
+ assert(2 === count($m->getRepeatedUint32()));
+ assert(2 === count($m->getRepeatedUint64()));
+ assert(2 === count($m->getRepeatedSint32()));
+ assert(2 === count($m->getRepeatedSint64()));
+ assert(2 === count($m->getRepeatedFixed32()));
+ assert(2 === count($m->getRepeatedFixed64()));
+ assert(2 === count($m->getRepeatedSfixed32()));
+ assert(2 === count($m->getRepeatedSfixed64()));
+ assert(2 === count($m->getRepeatedFloat()));
+ assert(2 === count($m->getRepeatedDouble()));
+ assert(2 === count($m->getRepeatedBool()));
+ assert(2 === count($m->getRepeatedEnum()));
+
+ assert(-42 === $m->getRepeatedInt32()[0]);
+ assert(-52 === $m->getRepeatedInt32()[1]);
+ assert(42 === $m->getRepeatedUint32()[0]);
+ assert(52 === $m->getRepeatedUint32()[1]);
+ assert(-44 === $m->getRepeatedSint32()[0]);
+ assert(-54 === $m->getRepeatedSint32()[1]);
+ assert(46 === $m->getRepeatedFixed32()[0]);
+ assert(56 === $m->getRepeatedFixed32()[1]);
+ assert(-46 === $m->getRepeatedSfixed32()[0]);
+ assert(-56 === $m->getRepeatedSfixed32()[1]);
+ assert(1.5 === $m->getRepeatedFloat()[0]);
+ assert(2.5 === $m->getRepeatedFloat()[1]);
+ assert(1.6 === $m->getRepeatedDouble()[0]);
+ assert(2.6 === $m->getRepeatedDouble()[1]);
+ assert(true === $m->getRepeatedBool()[0]);
+ assert(false === $m->getRepeatedBool()[1]);
+ assert(TestEnum::ONE === $m->getRepeatedEnum()[0]);
+ assert(TestEnum::ZERO === $m->getRepeatedEnum()[1]);
+ if (PHP_INT_SIZE == 4) {
+ assert('-43' === $m->getRepeatedInt64()[0]);
+ assert('-53' === $m->getRepeatedInt64()[1]);
+ assert('43' === $m->getRepeatedUint64()[0]);
+ assert('53' === $m->getRepeatedUint64()[1]);
+ assert('-45' === $m->getRepeatedSint64()[0]);
+ assert('-55' === $m->getRepeatedSint64()[1]);
+ assert('47' === $m->getRepeatedFixed64()[0]);
+ assert('57' === $m->getRepeatedFixed64()[1]);
+ assert('-47' === $m->getRepeatedSfixed64()[0]);
+ assert('-57' === $m->getRepeatedSfixed64()[1]);
+ } else {
+ assert(-43 === $m->getRepeatedInt64()[0]);
+ assert(-53 === $m->getRepeatedInt64()[1]);
+ assert(43 === $m->getRepeatedUint64()[0]);
+ assert(53 === $m->getRepeatedUint64()[1]);
+ assert(-45 === $m->getRepeatedSint64()[0]);
+ assert(-55 === $m->getRepeatedSint64()[1]);
+ assert(47 === $m->getRepeatedFixed64()[0]);
+ assert(57 === $m->getRepeatedFixed64()[1]);
+ assert(-47 === $m->getRepeatedSfixed64()[0]);
+ assert(-57 === $m->getRepeatedSfixed64()[1]);
+ }
+ }
+
+ public static function getGoldenTestPackedMessage()
+ {
+ return hex2bin(
+ "D2050AD6FFFFFF0FCCFFFFFF0F" .
+ "DA0514D5FFFFFFFFFFFFFFFF01CBFFFFFFFFFFFFFFFF01" .
+ "E205022A34" .
+ "EA05022B35" .
+ "F20502576B" .
+ "FA0502596D" .
+ "8206082E00000038000000" .
+ "8A06102F000000000000003900000000000000" .
+ "920608D2FFFFFFC8FFFFFF" .
+ "9A0610D1FFFFFFFFFFFFFFC7FFFFFFFFFFFFFF" .
+ "A206080000C03F00002040" .
+ "AA06109A9999999999F93FCDCCCCCCCCCC0440" .
+ "B206020100" .
+ "BA06020100"
+ );
+ }
+
+ public static function getGoldenTestUnpackedMessage()
+ {
+ return hex2bin(
+ "D005D6FFFFFF0FD005CCFFFFFF0F" .
+ "D805D5FFFFFFFFFFFFFFFF01D805CBFFFFFFFFFFFFFFFF01" .
+ "E0052AE00534" .
+ "E8052BE80535" .
+ "F00557F0056B" .
+ "F80559F8056D" .
+ "85062E000000850638000000" .
+ "89062F0000000000000089063900000000000000" .
+ "9506D2FFFFFF9506C8FFFFFF" .
+ "9906D1FFFFFFFFFFFFFF9906C7FFFFFFFFFFFFFF" .
+ "A5060000C03FA50600002040" .
+ "A9069A9999999999F93FA906CDCCCCCCCCCC0440" .
+ "B00601B00600" .
+ "B80601B80600"
+ );
+ }
+}
diff --git a/phpunit.xml b/phpunit.xml
new file mode 100644
index 00000000..d311c509
--- /dev/null
+++ b/phpunit.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<phpunit bootstrap="./vendor/autoload.php"
+ colors="true">
+ <testsuites>
+ <testsuite name="protobuf-tests">
+ <file>php/tests/php_implementation_test.php</file>
+ <file>php/tests/array_test.php</file>
+ <file>php/tests/encode_decode_test.php</file>
+ <file>php/tests/generated_class_test.php</file>
+ <file>php/tests/map_field_test.php</file>
+ </testsuite>
+ </testsuites>
+</phpunit>
diff --git a/post_process_dist.sh b/post_process_dist.sh
index 82736bd0..a5f95800 100755
--- a/post_process_dist.sh
+++ b/post_process_dist.sh
@@ -27,7 +27,7 @@ fi
set -ex
-LANGUAGES="cpp csharp java javanano js objectivec python ruby"
+LANGUAGES="cpp csharp java javanano js objectivec python ruby php"
BASENAME=`basename $1 .tar.gz`
VERSION=${BASENAME:9}
diff --git a/protobuf.bzl b/protobuf.bzl
index c5555fde..ac448201 100644
--- a/protobuf.bzl
+++ b/protobuf.bzl
@@ -15,14 +15,21 @@ def _GenDir(ctx):
return _GetPath(ctx, ctx.attr.includes[0])
return _GetPath(ctx, ctx.label.package + '/' + ctx.attr.includes[0])
-def _CcOuts(srcs, use_grpc_plugin=False):
- ret = [s[:-len(".proto")] + ".pb.h" for s in srcs] + \
- [s[:-len(".proto")] + ".pb.cc" for s in srcs]
+def _CcHdrs(srcs, use_grpc_plugin=False):
+ ret = [s[:-len(".proto")] + ".pb.h" for s in srcs]
+ if use_grpc_plugin:
+ ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs]
+ return ret
+
+def _CcSrcs(srcs, use_grpc_plugin=False):
+ ret = [s[:-len(".proto")] + ".pb.cc" for s in srcs]
if use_grpc_plugin:
- ret += [s[:-len(".proto")] + ".grpc.pb.h" for s in srcs] + \
- [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
+ ret += [s[:-len(".proto")] + ".grpc.pb.cc" for s in srcs]
return ret
+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]
@@ -62,16 +69,29 @@ def _proto_gen_impl(ctx):
if ctx.attr.gen_py:
args += ["--python_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
- if ctx.executable.grpc_cpp_plugin:
- args += ["--plugin=protoc-gen-grpc=" + ctx.executable.grpc_cpp_plugin.path]
- args += ["--grpc_out=" + ctx.var["GENDIR"] + "/" + gen_dir]
+ inputs = srcs + deps
+ if ctx.executable.plugin:
+ plugin = ctx.executable.plugin
+ lang = ctx.attr.plugin_language
+ if not lang and plugin.basename.startswith('protoc-gen-'):
+ lang = plugin.basename[len('protoc-gen-'):]
+ if not lang:
+ fail("cannot infer the target language of plugin", "plugin_language")
+
+ outdir = ctx.var["GENDIR"] + "/" + gen_dir
+ if ctx.attr.plugin_options:
+ outdir = ",".join(ctx.attr.plugin_options) + ":" + outdir
+ args += ["--plugin=protoc-gen-%s=%s" % (lang, plugin.path)]
+ args += ["--%s_out=%s" % (lang, outdir)]
+ inputs += [plugin]
if args:
ctx.action(
- inputs=srcs + deps,
+ inputs=inputs,
outputs=ctx.outputs.outs,
arguments=args + import_flags + [s.path for s in srcs],
executable=ctx.executable.protoc,
+ mnemonic="ProtoCompile",
)
return struct(
@@ -82,22 +102,24 @@ def _proto_gen_impl(ctx):
),
)
-_proto_gen = rule(
+proto_gen = rule(
attrs = {
"srcs": attr.label_list(allow_files = True),
"deps": attr.label_list(providers = ["proto"]),
"includes": attr.string_list(),
"protoc": attr.label(
- cfg = HOST_CFG,
+ cfg = "host",
executable = True,
single_file = True,
mandatory = True,
),
- "grpc_cpp_plugin": attr.label(
- cfg = HOST_CFG,
+ "plugin": attr.label(
+ cfg = "host",
+ allow_files = True,
executable = True,
- single_file = True,
),
+ "plugin_language": attr.string(),
+ "plugin_options": attr.string_list(),
"gen_cc": attr.bool(),
"gen_py": attr.bool(),
"outs": attr.output_list(),
@@ -105,6 +127,26 @@ _proto_gen = rule(
output_to_genfiles = True,
implementation = _proto_gen_impl,
)
+"""Generates codes from Protocol Buffers definitions.
+
+This rule helps you to implement Skylark macros specific to the target
+language. You should prefer more specific `cc_proto_library `,
+`py_proto_library` and others unless you are adding such wrapper macros.
+
+Args:
+ srcs: Protocol Buffers definition files (.proto) to run the protocol compiler
+ against.
+ deps: a list of dependency labels; must be other proto libraries.
+ includes: a list of include paths to .proto files.
+ protoc: the label of the protocol compiler to generate the sources.
+ plugin: the label of the protocol compiler plugin to be passed to the protocol
+ compiler.
+ plugin_language: the language of the generated sources
+ plugin_options: a list of options to be passed to the plugin
+ gen_cc: generates C++ sources in addition to the ones from the plugin.
+ gen_py: generates Python sources in addition to the ones from the plugin.
+ outs: a list of labels of the expected outputs from the protocol compiler.
+"""
def cc_proto_library(
name,
@@ -150,7 +192,7 @@ def cc_proto_library(
if internal_bootstrap_hack:
# For pre-checked-in generated files, we add the internal_bootstrap_hack
# which will skip the codegen action.
- _proto_gen(
+ proto_gen(
name=name + "_genproto",
srcs=srcs,
deps=[s + "_genproto" for s in deps],
@@ -168,15 +210,18 @@ def cc_proto_library(
if use_grpc_plugin:
grpc_cpp_plugin = "//external:grpc_cpp_plugin"
- outs = _CcOuts(srcs, use_grpc_plugin)
+ gen_srcs = _CcSrcs(srcs, use_grpc_plugin)
+ gen_hdrs = _CcHdrs(srcs, use_grpc_plugin)
+ outs = gen_srcs + gen_hdrs
- _proto_gen(
+ proto_gen(
name=name + "_genproto",
srcs=srcs,
deps=[s + "_genproto" for s in deps],
includes=includes,
protoc=protoc,
- grpc_cpp_plugin=grpc_cpp_plugin,
+ plugin=grpc_cpp_plugin,
+ plugin_language="grpc",
gen_cc=1,
outs=outs,
visibility=["//visibility:public"],
@@ -189,7 +234,8 @@ def cc_proto_library(
native.cc_library(
name=name,
- srcs=outs,
+ srcs=gen_srcs,
+ hdrs=gen_hdrs,
deps=cc_libs + deps,
includes=includes,
**kargs)
@@ -286,7 +332,7 @@ def py_proto_library(
if include != None:
includes = [include]
- _proto_gen(
+ proto_gen(
name=name + "_genproto",
srcs=srcs,
deps=[s + "_genproto" for s in deps],
diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml
index 840bc60a..680154b1 100644
--- a/protoc-artifacts/pom.xml
+++ b/protoc-artifacts/pom.xml
@@ -10,7 +10,7 @@
</parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protoc</artifactId>
- <version>3.0.0</version>
+ <version>3.1.0</version>
<packaging>pom</packaging>
<name>Protobuf Compiler</name>
<description>
diff --git a/python/google/protobuf/__init__.py b/python/google/protobuf/__init__.py
index 6210a404..0e2a89ff 100755
--- a/python/google/protobuf/__init__.py
+++ b/python/google/protobuf/__init__.py
@@ -30,7 +30,7 @@
# Copyright 2007 Google Inc. All Rights Reserved.
-__version__ = '3.0.0'
+__version__ = '3.1.0'
if __name__ != '__main__':
try:
diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py
index 873af306..e1f2e3b7 100755
--- a/python/google/protobuf/descriptor.py
+++ b/python/google/protobuf/descriptor.py
@@ -171,13 +171,6 @@ class _NestedDescriptorBase(DescriptorBase):
self._serialized_start = serialized_start
self._serialized_end = serialized_end
- def GetTopLevelContainingType(self):
- """Returns the root if this is a nested type, or itself if its the root."""
- desc = self
- while desc.containing_type is not None:
- desc = desc.containing_type
- return desc
-
def CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2.
@@ -497,7 +490,7 @@ class FieldDescriptor(DescriptorBase):
def __new__(cls, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
- has_default_value=True, containing_oneof=None):
+ has_default_value=True, containing_oneof=None, json_name=None):
_message.Message._CheckCalledFromGeneratedFile()
if is_extension:
return _message.default_pool.FindExtensionByName(full_name)
@@ -507,7 +500,7 @@ class FieldDescriptor(DescriptorBase):
def __init__(self, name, full_name, index, number, type, cpp_type, label,
default_value, message_type, enum_type, containing_type,
is_extension, extension_scope, options=None,
- has_default_value=True, containing_oneof=None):
+ has_default_value=True, containing_oneof=None, json_name=None):
"""The arguments are as described in the description of FieldDescriptor
attributes above.
@@ -519,6 +512,10 @@ class FieldDescriptor(DescriptorBase):
self.name = name
self.full_name = full_name
self._camelcase_name = None
+ if json_name is None:
+ self.json_name = _ToJsonName(name)
+ else:
+ self.json_name = json_name
self.index = index
self.number = number
self.type = type
@@ -894,6 +891,31 @@ def _ToCamelCase(name):
return ''.join(result)
+def _OptionsOrNone(descriptor_proto):
+ """Returns the value of the field `options`, or None if it is not set."""
+ if descriptor_proto.HasField('options'):
+ return descriptor_proto.options
+ else:
+ return None
+
+
+def _ToJsonName(name):
+ """Converts name to Json name and returns it."""
+ capitalize_next = False
+ result = []
+
+ for c in name:
+ if c == '_':
+ capitalize_next = True
+ elif capitalize_next:
+ result.append(c.upper())
+ capitalize_next = False
+ else:
+ result += c
+
+ return ''.join(result)
+
+
def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
syntax=None):
"""Make a protobuf Descriptor given a DescriptorProto protobuf.
@@ -970,6 +992,10 @@ def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
full_name = '.'.join(full_message_name + [field_proto.name])
enum_desc = None
nested_desc = None
+ if field_proto.json_name:
+ json_name = field_proto.json_name
+ else:
+ json_name = None
if field_proto.HasField('type_name'):
type_name = field_proto.type_name
full_type_name = '.'.join(full_message_name +
@@ -984,10 +1010,11 @@ def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
field_proto.number, field_proto.type,
FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),
field_proto.label, None, nested_desc, enum_desc, None, False, None,
- options=field_proto.options, has_default_value=False)
+ options=_OptionsOrNone(field_proto), has_default_value=False,
+ json_name=json_name)
fields.append(field)
desc_name = '.'.join(full_message_name)
return Descriptor(desc_proto.name, desc_name, None, None, fields,
list(nested_types.values()), list(enum_types.values()), [],
- options=desc_proto.options)
+ options=_OptionsOrNone(desc_proto))
diff --git a/python/google/protobuf/descriptor_pool.py b/python/google/protobuf/descriptor_pool.py
index 5c055ab9..5f43ee5f 100644
--- a/python/google/protobuf/descriptor_pool.py
+++ b/python/google/protobuf/descriptor_pool.py
@@ -62,7 +62,7 @@ from google.protobuf import descriptor_database
from google.protobuf import text_encoding
-_USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS
+_USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access
def _NormalizeFullyQualifiedName(name):
@@ -80,6 +80,14 @@ def _NormalizeFullyQualifiedName(name):
return name.lstrip('.')
+def _OptionsOrNone(descriptor_proto):
+ """Returns the value of the field `options`, or None if it is not set."""
+ if descriptor_proto.HasField('options'):
+ return descriptor_proto.options
+ else:
+ return None
+
+
class DescriptorPool(object):
"""A collection of protobufs dynamically constructed by descriptor protos."""
@@ -326,78 +334,61 @@ class DescriptorPool(object):
name=file_proto.name,
package=file_proto.package,
syntax=file_proto.syntax,
- options=file_proto.options,
+ options=_OptionsOrNone(file_proto),
serialized_pb=file_proto.SerializeToString(),
dependencies=direct_deps,
public_dependencies=public_deps)
- if _USE_C_DESCRIPTORS:
- # When using C++ descriptors, all objects defined in the file were added
- # to the C++ database when the FileDescriptor was built above.
- # Just add them to this descriptor pool.
- def _AddMessageDescriptor(message_desc):
- self._descriptors[message_desc.full_name] = message_desc
- for nested in message_desc.nested_types:
- _AddMessageDescriptor(nested)
- for enum_type in message_desc.enum_types:
- _AddEnumDescriptor(enum_type)
- def _AddEnumDescriptor(enum_desc):
- self._enum_descriptors[enum_desc.full_name] = enum_desc
- for message_type in file_descriptor.message_types_by_name.values():
- _AddMessageDescriptor(message_type)
- for enum_type in file_descriptor.enum_types_by_name.values():
- _AddEnumDescriptor(enum_type)
+ scope = {}
+
+ # This loop extracts all the message and enum types from all the
+ # dependencies of the file_proto. This is necessary to create the
+ # scope of available message types when defining the passed in
+ # file proto.
+ for dependency in built_deps:
+ scope.update(self._ExtractSymbols(
+ dependency.message_types_by_name.values()))
+ scope.update((_PrefixWithDot(enum.full_name), enum)
+ for enum in dependency.enum_types_by_name.values())
+
+ for message_type in file_proto.message_type:
+ message_desc = self._ConvertMessageDescriptor(
+ message_type, file_proto.package, file_descriptor, scope,
+ file_proto.syntax)
+ file_descriptor.message_types_by_name[message_desc.name] = (
+ message_desc)
+
+ for enum_type in file_proto.enum_type:
+ file_descriptor.enum_types_by_name[enum_type.name] = (
+ self._ConvertEnumDescriptor(enum_type, file_proto.package,
+ file_descriptor, None, scope))
+
+ for index, extension_proto in enumerate(file_proto.extension):
+ extension_desc = self._MakeFieldDescriptor(
+ extension_proto, file_proto.package, index, is_extension=True)
+ extension_desc.containing_type = self._GetTypeFromScope(
+ file_descriptor.package, extension_proto.extendee, scope)
+ self._SetFieldType(extension_proto, extension_desc,
+ file_descriptor.package, scope)
+ file_descriptor.extensions_by_name[extension_desc.name] = (
+ extension_desc)
+
+ for desc_proto in file_proto.message_type:
+ self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
+
+ if file_proto.package:
+ desc_proto_prefix = _PrefixWithDot(file_proto.package)
else:
- scope = {}
-
- # This loop extracts all the message and enum types from all the
- # dependencies of the file_proto. This is necessary to create the
- # scope of available message types when defining the passed in
- # file proto.
- for dependency in built_deps:
- scope.update(self._ExtractSymbols(
- dependency.message_types_by_name.values()))
- scope.update((_PrefixWithDot(enum.full_name), enum)
- for enum in dependency.enum_types_by_name.values())
-
- for message_type in file_proto.message_type:
- message_desc = self._ConvertMessageDescriptor(
- message_type, file_proto.package, file_descriptor, scope,
- file_proto.syntax)
- file_descriptor.message_types_by_name[message_desc.name] = (
- message_desc)
-
- for enum_type in file_proto.enum_type:
- file_descriptor.enum_types_by_name[enum_type.name] = (
- self._ConvertEnumDescriptor(enum_type, file_proto.package,
- file_descriptor, None, scope))
-
- for index, extension_proto in enumerate(file_proto.extension):
- extension_desc = self._MakeFieldDescriptor(
- extension_proto, file_proto.package, index, is_extension=True)
- extension_desc.containing_type = self._GetTypeFromScope(
- file_descriptor.package, extension_proto.extendee, scope)
- self._SetFieldType(extension_proto, extension_desc,
- file_descriptor.package, scope)
- file_descriptor.extensions_by_name[extension_desc.name] = (
- extension_desc)
-
- for desc_proto in file_proto.message_type:
- self._SetAllFieldTypes(file_proto.package, desc_proto, scope)
-
- if file_proto.package:
- desc_proto_prefix = _PrefixWithDot(file_proto.package)
- else:
- desc_proto_prefix = ''
+ desc_proto_prefix = ''
- for desc_proto in file_proto.message_type:
- desc = self._GetTypeFromScope(
- desc_proto_prefix, desc_proto.name, scope)
- file_descriptor.message_types_by_name[desc_proto.name] = desc
+ for desc_proto in file_proto.message_type:
+ desc = self._GetTypeFromScope(
+ desc_proto_prefix, desc_proto.name, scope)
+ file_descriptor.message_types_by_name[desc_proto.name] = desc
- for index, service_proto in enumerate(file_proto.service):
- file_descriptor.services_by_name[service_proto.name] = (
- self._MakeServiceDescriptor(service_proto, index, scope,
- file_proto.package, file_descriptor))
+ for index, service_proto in enumerate(file_proto.service):
+ file_descriptor.services_by_name[service_proto.name] = (
+ self._MakeServiceDescriptor(service_proto, index, scope,
+ file_proto.package, file_descriptor))
self.Add(file_proto)
self._file_descriptors[file_proto.name] = file_descriptor
@@ -413,6 +404,7 @@ class DescriptorPool(object):
package: The package the proto should be located in.
file_desc: The file containing this message.
scope: Dict mapping short and full symbols to message and enum types.
+ syntax: string indicating syntax of the file ("proto2" or "proto3")
Returns:
The added descriptor.
@@ -463,7 +455,7 @@ class DescriptorPool(object):
nested_types=nested,
enum_types=enums,
extensions=extensions,
- options=desc_proto.options,
+ options=_OptionsOrNone(desc_proto),
is_extendable=is_extendable,
extension_ranges=extension_ranges,
file=file_desc,
@@ -517,7 +509,7 @@ class DescriptorPool(object):
file=file_desc,
values=values,
containing_type=containing_type,
- options=enum_proto.options)
+ options=_OptionsOrNone(enum_proto))
scope['.%s' % enum_name] = desc
self._enum_descriptors[enum_name] = desc
return desc
@@ -562,7 +554,7 @@ class DescriptorPool(object):
default_value=None,
is_extension=is_extension,
extension_scope=None,
- options=field_proto.options)
+ options=_OptionsOrNone(field_proto))
def _SetAllFieldTypes(self, package, desc_proto, scope):
"""Sets all the descriptor's fields's types.
@@ -681,7 +673,7 @@ class DescriptorPool(object):
name=value_proto.name,
index=index,
number=value_proto.number,
- options=value_proto.options,
+ options=_OptionsOrNone(value_proto),
type=None)
def _MakeServiceDescriptor(self, service_proto, service_index, scope,
@@ -711,7 +703,7 @@ class DescriptorPool(object):
full_name=service_name,
index=service_index,
methods=methods,
- options=service_proto.options,
+ options=_OptionsOrNone(service_proto),
file=file_desc)
return desc
@@ -740,7 +732,7 @@ class DescriptorPool(object):
containing_service=None,
input_type=input_type,
output_type=output_type,
- options=method_proto.options)
+ options=_OptionsOrNone(method_proto))
def _ExtractSymbols(self, descriptors):
"""Pulls out all the symbols from descriptor protos.
diff --git a/python/google/protobuf/internal/any_test.proto b/python/google/protobuf/internal/any_test.proto
index cd641ca0..76a7ebd6 100644
--- a/python/google/protobuf/internal/any_test.proto
+++ b/python/google/protobuf/internal/any_test.proto
@@ -30,13 +30,21 @@
// Author: jieluo@google.com (Jie Luo)
-syntax = "proto3";
+syntax = "proto2";
package google.protobuf.internal;
import "google/protobuf/any.proto";
message TestAny {
- google.protobuf.Any value = 1;
- int32 int_value = 2;
+ optional google.protobuf.Any value = 1;
+ optional int32 int_value = 2;
+ extensions 10 to max;
+}
+
+message TestAnyExtension1 {
+ extend TestAny {
+ optional TestAnyExtension1 extension1 = 98418603;
+ }
+ optional int32 i = 15;
}
diff --git a/python/google/protobuf/internal/containers.py b/python/google/protobuf/internal/containers.py
index ce46d08c..de13018e 100755
--- a/python/google/protobuf/internal/containers.py
+++ b/python/google/protobuf/internal/containers.py
@@ -436,9 +436,11 @@ class ScalarMap(MutableMapping):
"""Simple, type-checked, dict-like container for holding repeated scalars."""
# Disallows assignment to other attributes.
- __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener']
+ __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener',
+ '_entry_descriptor']
- def __init__(self, message_listener, key_checker, value_checker):
+ def __init__(self, message_listener, key_checker, value_checker,
+ entry_descriptor):
"""
Args:
message_listener: A MessageListener implementation.
@@ -448,10 +450,12 @@ class ScalarMap(MutableMapping):
inserted into this container.
value_checker: A type_checkers.ValueChecker instance to run on values
inserted into this container.
+ entry_descriptor: The MessageDescriptor of a map entry: key and value.
"""
self._message_listener = message_listener
self._key_checker = key_checker
self._value_checker = value_checker
+ self._entry_descriptor = entry_descriptor
self._values = {}
def __getitem__(self, key):
@@ -513,6 +517,9 @@ class ScalarMap(MutableMapping):
self._values.clear()
self._message_listener.Modified()
+ def GetEntryClass(self):
+ return self._entry_descriptor._concrete_class
+
class MessageMap(MutableMapping):
@@ -520,9 +527,10 @@ class MessageMap(MutableMapping):
# Disallows assignment to other attributes.
__slots__ = ['_key_checker', '_values', '_message_listener',
- '_message_descriptor']
+ '_message_descriptor', '_entry_descriptor']
- def __init__(self, message_listener, message_descriptor, key_checker):
+ def __init__(self, message_listener, message_descriptor, key_checker,
+ entry_descriptor):
"""
Args:
message_listener: A MessageListener implementation.
@@ -532,10 +540,12 @@ class MessageMap(MutableMapping):
inserted into this container.
value_checker: A type_checkers.ValueChecker instance to run on values
inserted into this container.
+ entry_descriptor: The MessageDescriptor of a map entry: key and value.
"""
self._message_listener = message_listener
self._message_descriptor = message_descriptor
self._key_checker = key_checker
+ self._entry_descriptor = entry_descriptor
self._values = {}
def __getitem__(self, key):
@@ -613,3 +623,6 @@ class MessageMap(MutableMapping):
def clear(self):
self._values.clear()
self._message_listener.Modified()
+
+ def GetEntryClass(self):
+ return self._entry_descriptor._concrete_class
diff --git a/python/google/protobuf/internal/descriptor_pool_test.py b/python/google/protobuf/internal/descriptor_pool_test.py
index 3c8c7935..d4de2d81 100644
--- a/python/google/protobuf/internal/descriptor_pool_test.py
+++ b/python/google/protobuf/internal/descriptor_pool_test.py
@@ -119,6 +119,7 @@ class DescriptorPoolTest(unittest.TestCase):
self.assertEqual('google.protobuf.python.internal.Factory1Message',
msg1.full_name)
self.assertEqual(None, msg1.containing_type)
+ self.assertFalse(msg1.has_options)
nested_msg1 = msg1.nested_types[0]
self.assertEqual('NestedFactory1Message', nested_msg1.name)
@@ -202,6 +203,7 @@ class DescriptorPoolTest(unittest.TestCase):
self.assertIsInstance(enum1, descriptor.EnumDescriptor)
self.assertEqual(0, enum1.values_by_name['FACTORY_1_VALUE_0'].number)
self.assertEqual(1, enum1.values_by_name['FACTORY_1_VALUE_1'].number)
+ self.assertFalse(enum1.has_options)
nested_enum1 = self.pool.FindEnumTypeByName(
'google.protobuf.python.internal.Factory1Message.NestedFactory1Enum')
@@ -234,6 +236,8 @@ class DescriptorPoolTest(unittest.TestCase):
'google.protobuf.python.internal.Factory1Message.list_value')
self.assertEqual(field.name, 'list_value')
self.assertEqual(field.label, field.LABEL_REPEATED)
+ self.assertFalse(field.has_options)
+
with self.assertRaises(KeyError):
self.pool.FindFieldByName('Does not exist')
@@ -448,6 +452,7 @@ class EnumField(object):
test.assertTrue(field_desc.has_default_value)
test.assertEqual(enum_desc.values_by_name[self.default_value].number,
field_desc.default_value)
+ test.assertFalse(enum_desc.values_by_name[self.default_value].has_options)
test.assertEqual(msg_desc, field_desc.containing_type)
test.assertEqual(enum_desc, field_desc.enum_type)
diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py
index 623198c8..1f148ab9 100755
--- a/python/google/protobuf/internal/descriptor_test.py
+++ b/python/google/protobuf/internal/descriptor_test.py
@@ -766,6 +766,8 @@ class MakeDescriptorTest(unittest.TestCase):
'Foo2.Sub.bar_field')
self.assertEqual(result.nested_types[0].fields[0].enum_type,
result.nested_types[0].enum_types[0])
+ self.assertFalse(result.has_options)
+ self.assertFalse(result.fields[0].has_options)
def testMakeDescriptorWithUnsignedIntField(self):
file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
@@ -818,6 +820,23 @@ class MakeDescriptorTest(unittest.TestCase):
self.assertEqual(result.fields[index].camelcase_name,
camelcase_names[index])
+ def testJsonName(self):
+ descriptor_proto = descriptor_pb2.DescriptorProto()
+ descriptor_proto.name = 'TestJsonName'
+ names = ['field_name', 'fieldName', 'FieldName',
+ '_field_name', 'FIELD_NAME', 'json_name']
+ json_names = ['fieldName', 'fieldName', 'FieldName',
+ 'FieldName', 'FIELDNAME', '@type']
+ for index in range(len(names)):
+ field = descriptor_proto.field.add()
+ field.number = index + 1
+ field.name = names[index]
+ field.json_name = '@type'
+ result = descriptor.MakeDescriptor(descriptor_proto)
+ for index in range(len(json_names)):
+ self.assertEqual(result.fields[index].json_name,
+ json_names[index])
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/generator_test.py b/python/google/protobuf/internal/generator_test.py
index 83ea5f50..7f13f9da 100755
--- a/python/google/protobuf/internal/generator_test.py
+++ b/python/google/protobuf/internal/generator_test.py
@@ -227,7 +227,8 @@ class GeneratorTest(unittest.TestCase):
[unittest_import_pb2.DESCRIPTOR])
self.assertEqual(unittest_import_pb2.DESCRIPTOR.dependencies,
[unittest_import_public_pb2.DESCRIPTOR])
-
+ self.assertEqual(unittest_import_pb2.DESCRIPTOR.public_dependencies,
+ [unittest_import_public_pb2.DESCRIPTOR])
def testNoGenericServices(self):
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage"))
self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO"))
diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py
index a5ee8ace..5ed65622 100644
--- a/python/google/protobuf/internal/json_format_test.py
+++ b/python/google/protobuf/internal/json_format_test.py
@@ -205,6 +205,15 @@ class JsonFormatTest(JsonFormatBase):
parsed_message = json_format_proto3_pb2.TestMessage()
self.CheckParseBack(message, parsed_message)
+ def testIntegersRepresentedAsFloat(self):
+ message = json_format_proto3_pb2.TestMessage()
+ json_format.Parse('{"int32Value": -2.147483648e9}', message)
+ self.assertEqual(message.int32_value, -2147483648)
+ json_format.Parse('{"int32Value": 1e5}', message)
+ self.assertEqual(message.int32_value, 100000)
+ json_format.Parse('{"int32Value": 1.0}', message)
+ self.assertEqual(message.int32_value, 1)
+
def testMapFields(self):
message = json_format_proto3_pb2.TestMap()
message.bool_map[True] = 1
@@ -428,6 +437,9 @@ class JsonFormatTest(JsonFormatBase):
' "value": "hello",'
' "repeatedValue": [11.1, false, null, null]'
'}'))
+ message.Clear()
+ json_format.Parse('{"value": null}', message)
+ self.assertEqual(message.value.WhichOneof('kind'), 'null_value')
def testListValueMessage(self):
message = json_format_proto3_pb2.TestListValue()
@@ -600,6 +612,11 @@ class JsonFormatTest(JsonFormatBase):
'}',
parsed_message)
self.assertEqual(message, parsed_message)
+ # Null and {} should have different behavior for sub message.
+ self.assertFalse(parsed_message.HasField('message_value'))
+ json_format.Parse('{"messageValue": {}}', parsed_message)
+ self.assertTrue(parsed_message.HasField('message_value'))
+ # Null is not allowed to be used as an element in repeated field.
self.assertRaisesRegexp(
json_format.ParseError,
'Failed to parse repeatedInt32Value field: '
@@ -621,15 +638,16 @@ class JsonFormatTest(JsonFormatBase):
self.CheckError('',
r'Failed to load JSON: (Expecting value)|(No JSON).')
- def testParseBadEnumValue(self):
- self.CheckError(
- '{"enumValue": 1}',
- 'Enum value must be a string literal with double quotes. '
- 'Type "proto3.EnumType" has no value named 1.')
+ def testParseEnumValue(self):
+ message = json_format_proto3_pb2.TestMessage()
+ text = '{"enumValue": 0}'
+ json_format.Parse(text, message)
+ text = '{"enumValue": 1}'
+ json_format.Parse(text, message)
self.CheckError(
'{"enumValue": "baz"}',
- 'Enum value must be a string literal with double quotes. '
- 'Type "proto3.EnumType" has no value named baz.')
+ 'Failed to parse enumValue field: Invalid enum value baz '
+ 'for enum type proto3.EnumType.')
def testParseBadIdentifer(self):
self.CheckError('{int32Value: 1}',
@@ -672,12 +690,12 @@ class JsonFormatTest(JsonFormatBase):
text = '{"int32Value": 0x12345}'
self.assertRaises(json_format.ParseError,
json_format.Parse, text, message)
+ self.CheckError('{"int32Value": 1.5}',
+ 'Failed to parse int32Value field: '
+ 'Couldn\'t parse integer: 1.5.')
self.CheckError('{"int32Value": 012345}',
(r'Failed to load JSON: Expecting \'?,\'? delimiter: '
r'line 1.'))
- self.CheckError('{"int32Value": 1.0}',
- 'Failed to parse int32Value field: '
- 'Couldn\'t parse integer: 1.0.')
self.CheckError('{"int32Value": " 1 "}',
'Failed to parse int32Value field: '
'Couldn\'t parse integer: " 1 ".')
@@ -687,9 +705,6 @@ class JsonFormatTest(JsonFormatBase):
self.CheckError('{"int32Value": 12345678901234567890}',
'Failed to parse int32Value field: Value out of range: '
'12345678901234567890.')
- self.CheckError('{"int32Value": 1e5}',
- 'Failed to parse int32Value field: '
- 'Couldn\'t parse integer: 100000.0.')
self.CheckError('{"uint32Value": -1}',
'Failed to parse uint32Value field: '
'Value out of range: -1.')
@@ -810,6 +825,43 @@ class JsonFormatTest(JsonFormatBase):
r'"value": 1234}')
json_format.Parse(text, message)
+ def testPreservingProtoFieldNames(self):
+ message = json_format_proto3_pb2.TestMessage()
+ message.int32_value = 12345
+ self.assertEqual('{\n "int32Value": 12345\n}',
+ json_format.MessageToJson(message))
+ self.assertEqual('{\n "int32_value": 12345\n}',
+ json_format.MessageToJson(message, False, True))
+
+ # Parsers accept both original proto field names and lowerCamelCase names.
+ message = json_format_proto3_pb2.TestMessage()
+ json_format.Parse('{"int32Value": 54321}', message)
+ self.assertEqual(54321, message.int32_value)
+ json_format.Parse('{"int32_value": 12345}', message)
+ self.assertEqual(12345, message.int32_value)
+
+ def testParseDict(self):
+ expected = 12345
+ js_dict = {'int32Value': expected}
+ message = json_format_proto3_pb2.TestMessage()
+ json_format.ParseDict(js_dict, message)
+ self.assertEqual(expected, message.int32_value)
+
+ def testMessageToDict(self):
+ message = json_format_proto3_pb2.TestMessage()
+ message.int32_value = 12345
+ expected = {'int32Value': 12345}
+ self.assertEqual(expected,
+ json_format.MessageToDict(message))
+
+ def testJsonName(self):
+ message = json_format_proto3_pb2.TestCustomJsonName()
+ message.value = 12345
+ self.assertEqual('{\n "@value": 12345\n}',
+ json_format.MessageToJson(message))
+ parsed_message = json_format_proto3_pb2.TestCustomJsonName()
+ self.CheckParseBack(message, parsed_message)
+
if __name__ == '__main__':
unittest.main()
diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py
index 1e95adf9..9986c0d9 100755
--- a/python/google/protobuf/internal/message_test.py
+++ b/python/google/protobuf/internal/message_test.py
@@ -67,6 +67,7 @@ from google.protobuf import text_format
from google.protobuf.internal import api_implementation
from google.protobuf.internal import packed_field_test_pb2
from google.protobuf.internal import test_util
+from google.protobuf.internal import testing_refleaks
from google.protobuf import message
from google.protobuf.internal import _parameterized
@@ -88,10 +89,13 @@ def IsNegInf(val):
return isinf(val) and (val < 0)
-@_parameterized.Parameters(
- (unittest_pb2),
- (unittest_proto3_arena_pb2))
-class MessageTest(unittest.TestCase):
+BaseTestCase = testing_refleaks.BaseTestCase
+
+
+@_parameterized.NamedParameters(
+ ('_proto2', unittest_pb2),
+ ('_proto3', unittest_proto3_arena_pb2))
+class MessageTest(BaseTestCase):
def testBadUtf8String(self, message_module):
if api_implementation.Type() != 'python':
@@ -957,7 +961,7 @@ class MessageTest(unittest.TestCase):
# Class to test proto2-only features (required, extensions, etc.)
-class Proto2Test(unittest.TestCase):
+class Proto2Test(BaseTestCase):
def testFieldPresence(self):
message = unittest_pb2.TestAllTypes()
@@ -1113,6 +1117,7 @@ class Proto2Test(unittest.TestCase):
optional_bytes=b'x',
optionalgroup={'a': 400},
optional_nested_message={'bb': 500},
+ optional_foreign_message={},
optional_nested_enum='BAZ',
repeatedgroup=[{'a': 600},
{'a': 700}],
@@ -1125,8 +1130,12 @@ class Proto2Test(unittest.TestCase):
self.assertEqual(300.5, message.optional_float)
self.assertEqual(b'x', message.optional_bytes)
self.assertEqual(400, message.optionalgroup.a)
- self.assertIsInstance(message.optional_nested_message, unittest_pb2.TestAllTypes.NestedMessage)
+ self.assertIsInstance(message.optional_nested_message,
+ unittest_pb2.TestAllTypes.NestedMessage)
self.assertEqual(500, message.optional_nested_message.bb)
+ self.assertTrue(message.HasField('optional_foreign_message'))
+ self.assertEqual(message.optional_foreign_message,
+ unittest_pb2.ForeignMessage())
self.assertEqual(unittest_pb2.TestAllTypes.BAZ,
message.optional_nested_enum)
self.assertEqual(2, len(message.repeatedgroup))
@@ -1164,7 +1173,7 @@ class Proto2Test(unittest.TestCase):
# Class to test proto3-only features/behavior (updated field presence & enums)
-class Proto3Test(unittest.TestCase):
+class Proto3Test(BaseTestCase):
# Utility method for comparing equality with a map.
def assertMapIterEquals(self, map_iter, dict_value):
@@ -1720,7 +1729,7 @@ class Proto3Test(unittest.TestCase):
-class ValidTypeNamesTest(unittest.TestCase):
+class ValidTypeNamesTest(BaseTestCase):
def assertImportFromName(self, msg, base_name):
# Parse <type 'module.class_name'> to extra 'some.name' as a string.
@@ -1741,7 +1750,7 @@ class ValidTypeNamesTest(unittest.TestCase):
self.assertImportFromName(pb.repeated_int32, 'Scalar')
self.assertImportFromName(pb.repeated_nested_message, 'Composite')
-class PackedFieldTest(unittest.TestCase):
+class PackedFieldTest(BaseTestCase):
def setMessage(self, message):
message.repeated_int32.append(1)
@@ -1800,10 +1809,14 @@ class PackedFieldTest(unittest.TestCase):
@unittest.skipIf(api_implementation.Type() != 'cpp',
'explicit tests of the C++ implementation')
-class OversizeProtosTest(unittest.TestCase):
-
- def setUp(self):
- self.file_desc = """
+class OversizeProtosTest(BaseTestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ # At the moment, reference cycles between DescriptorPool and Message classes
+ # are not detected and these objects are never freed.
+ # To avoid errors with ReferenceLeakChecker, we create the class only once.
+ file_desc = """
name: "f/f.msg2"
package: "f"
message_type {
@@ -1828,10 +1841,12 @@ class OversizeProtosTest(unittest.TestCase):
"""
pool = descriptor_pool.DescriptorPool()
desc = descriptor_pb2.FileDescriptorProto()
- text_format.Parse(self.file_desc, desc)
+ text_format.Parse(file_desc, desc)
pool.Add(desc)
- self.proto_cls = message_factory.MessageFactory(pool).GetPrototype(
+ cls.proto_cls = message_factory.MessageFactory(pool).GetPrototype(
pool.FindMessageTypeByName('f.msg2'))
+
+ def setUp(self):
self.p = self.proto_cls()
self.p.field.payload = 'c' * (1024 * 1024 * 64 + 1)
self.p_serialized = self.p.SerializeToString()
diff --git a/python/google/protobuf/internal/python_message.py b/python/google/protobuf/internal/python_message.py
index c0d0ad45..dc6565d4 100755
--- a/python/google/protobuf/internal/python_message.py
+++ b/python/google/protobuf/internal/python_message.py
@@ -63,7 +63,10 @@ except ImportError:
# nothing like hermetic Python. This means lesser control on the system and
# the six.moves package may be missing (is missing on 20150321 on gMac). Be
# extra conservative and try to load the old replacement if it fails.
- import copy_reg as copyreg
+ try:
+ import copy_reg as copyreg #PY26
+ except ImportError:
+ import copyreg
# We use "as" to avoid name collisions with variables.
from google.protobuf.internal import containers
@@ -380,13 +383,15 @@ def _GetInitializeDefaultForMap(field):
if _IsMessageMapField(field):
def MakeMessageMapDefault(message):
return containers.MessageMap(
- message._listener_for_children, value_field.message_type, key_checker)
+ message._listener_for_children, value_field.message_type, key_checker,
+ field.message_type)
return MakeMessageMapDefault
else:
value_checker = type_checkers.GetTypeChecker(value_field)
def MakePrimitiveMapDefault(message):
return containers.ScalarMap(
- message._listener_for_children, key_checker, value_checker)
+ message._listener_for_children, key_checker, value_checker,
+ field.message_type)
return MakePrimitiveMapDefault
def _DefaultValueConstructorForField(field):
diff --git a/python/google/protobuf/internal/reflection_test.py b/python/google/protobuf/internal/reflection_test.py
index 20e5d245..dad79c37 100755
--- a/python/google/protobuf/internal/reflection_test.py
+++ b/python/google/protobuf/internal/reflection_test.py
@@ -60,9 +60,13 @@ from google.protobuf.internal import more_messages_pb2
from google.protobuf.internal import message_set_extensions_pb2
from google.protobuf.internal import wire_format
from google.protobuf.internal import test_util
+from google.protobuf.internal import testing_refleaks
from google.protobuf.internal import decoder
+BaseTestCase = testing_refleaks.BaseTestCase
+
+
class _MiniDecoder(object):
"""Decodes a stream of values from a string.
@@ -108,7 +112,7 @@ class _MiniDecoder(object):
return self._pos == len(self._bytes)
-class ReflectionTest(unittest.TestCase):
+class ReflectionTest(BaseTestCase):
def assertListsEqual(self, values, others):
self.assertEqual(len(values), len(others))
@@ -636,7 +640,7 @@ class ReflectionTest(unittest.TestCase):
if struct.calcsize('L') == 4:
# Python only has signed ints, so 32-bit python can't fit an uint32
# in an int.
- TestGetAndDeserialize('optional_uint32', 1 << 31, long)
+ TestGetAndDeserialize('optional_uint32', 1 << 31, integer_64)
else:
# 64-bit python can fit uint32 inside an int
TestGetAndDeserialize('optional_uint32', 1 << 31, int)
@@ -1552,6 +1556,20 @@ class ReflectionTest(unittest.TestCase):
self.assertFalse(proto.HasField('optional_foreign_message'))
self.assertEqual(0, proto.optional_foreign_message.c)
+ def testDisconnectingInOneof(self):
+ m = unittest_pb2.TestOneof2() # This message has two messages in a oneof.
+ m.foo_message.qux_int = 5
+ sub_message = m.foo_message
+ # Accessing another message's field does not clear the first one
+ self.assertEqual(m.foo_lazy_message.qux_int, 0)
+ self.assertEqual(m.foo_message.qux_int, 5)
+ # But mutating another message in the oneof detaches the first one.
+ m.foo_lazy_message.qux_int = 6
+ self.assertEqual(m.foo_message.qux_int, 0)
+ # The reference we got above was detached and is still valid.
+ self.assertEqual(sub_message.qux_int, 5)
+ sub_message.qux_int = 7
+
def testOneOf(self):
proto = unittest_pb2.TestAllTypes()
proto.oneof_uint32 = 10
@@ -1810,7 +1828,7 @@ class ReflectionTest(unittest.TestCase):
# into separate TestCase classes.
-class TestAllTypesEqualityTest(unittest.TestCase):
+class TestAllTypesEqualityTest(BaseTestCase):
def setUp(self):
self.first_proto = unittest_pb2.TestAllTypes()
@@ -1826,7 +1844,7 @@ class TestAllTypesEqualityTest(unittest.TestCase):
self.assertEqual(self.first_proto, self.second_proto)
-class FullProtosEqualityTest(unittest.TestCase):
+class FullProtosEqualityTest(BaseTestCase):
"""Equality tests using completely-full protos as a starting point."""
@@ -1912,7 +1930,7 @@ class FullProtosEqualityTest(unittest.TestCase):
self.assertEqual(self.first_proto, self.second_proto)
-class ExtensionEqualityTest(unittest.TestCase):
+class ExtensionEqualityTest(BaseTestCase):
def testExtensionEquality(self):
first_proto = unittest_pb2.TestAllExtensions()
@@ -1945,7 +1963,7 @@ class ExtensionEqualityTest(unittest.TestCase):
self.assertEqual(first_proto, second_proto)
-class MutualRecursionEqualityTest(unittest.TestCase):
+class MutualRecursionEqualityTest(BaseTestCase):
def testEqualityWithMutualRecursion(self):
first_proto = unittest_pb2.TestMutualRecursionA()
@@ -1957,7 +1975,7 @@ class MutualRecursionEqualityTest(unittest.TestCase):
self.assertEqual(first_proto, second_proto)
-class ByteSizeTest(unittest.TestCase):
+class ByteSizeTest(BaseTestCase):
def setUp(self):
self.proto = unittest_pb2.TestAllTypes()
@@ -2253,7 +2271,7 @@ class ByteSizeTest(unittest.TestCase):
# * Handling of empty submessages (with and without "has"
# bits set).
-class SerializationTest(unittest.TestCase):
+class SerializationTest(BaseTestCase):
def testSerializeEmtpyMessage(self):
first_proto = unittest_pb2.TestAllTypes()
@@ -2814,7 +2832,7 @@ class SerializationTest(unittest.TestCase):
self.assertEqual(3, proto.repeated_int32[2])
-class OptionsTest(unittest.TestCase):
+class OptionsTest(BaseTestCase):
def testMessageOptions(self):
proto = message_set_extensions_pb2.TestMessageSet()
@@ -2841,7 +2859,7 @@ class OptionsTest(unittest.TestCase):
-class ClassAPITest(unittest.TestCase):
+class ClassAPITest(BaseTestCase):
@unittest.skipIf(
api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
@@ -2924,6 +2942,9 @@ class ClassAPITest(unittest.TestCase):
text_format.Merge(file_descriptor_str, file_descriptor)
return file_descriptor.SerializeToString()
+ @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable')
+ # This test can only run once; the second time, it raises errors about
+ # conflicting message descriptors.
def testParsingFlatClassWithExplicitClassDeclaration(self):
"""Test that the generated class can parse a flat message."""
# TODO(xiaofeng): This test fails with cpp implemetnation in the call
@@ -2948,6 +2969,7 @@ class ClassAPITest(unittest.TestCase):
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
+ @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable')
def testParsingFlatClass(self):
"""Test that the generated class can parse a flat message."""
file_descriptor = descriptor_pb2.FileDescriptorProto()
@@ -2963,6 +2985,7 @@ class ClassAPITest(unittest.TestCase):
text_format.Merge(msg_str, msg)
self.assertEqual(msg.flat, [0, 1, 2])
+ @testing_refleaks.SkipReferenceLeakChecker('MakeDescriptor is not repeatable')
def testParsingNestedClass(self):
"""Test that the generated class can parse a nested message."""
file_descriptor = descriptor_pb2.FileDescriptorProto()
diff --git a/python/google/protobuf/internal/testing_refleaks.py b/python/google/protobuf/internal/testing_refleaks.py
new file mode 100644
index 00000000..c461a9f4
--- /dev/null
+++ b/python/google/protobuf/internal/testing_refleaks.py
@@ -0,0 +1,128 @@
+# 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.
+
+"""A subclass of unittest.TestCase which checks for reference leaks.
+
+To use:
+- Use testing_refleak.BaseTestCase instead of unittest.TestCase
+- Configure and compile Python with --with-pydebug
+
+If sys.gettotalrefcount() is not available (because Python was built without
+the Py_DEBUG option), then this module is a no-op and tests will run normally.
+"""
+
+import gc
+import sys
+
+try:
+ import copy_reg as copyreg #PY26
+except ImportError:
+ import copyreg
+
+try:
+ import unittest2 as unittest #PY26
+except ImportError:
+ import unittest
+
+
+class LocalTestResult(unittest.TestResult):
+ """A TestResult which forwards events to a parent object, except for Skips."""
+
+ def __init__(self, parent_result):
+ unittest.TestResult.__init__(self)
+ self.parent_result = parent_result
+
+ def addError(self, test, error):
+ self.parent_result.addError(test, error)
+
+ def addFailure(self, test, error):
+ self.parent_result.addFailure(test, error)
+
+ def addSkip(self, test, reason):
+ pass
+
+
+class ReferenceLeakCheckerTestCase(unittest.TestCase):
+ """A TestCase which runs tests multiple times, collecting reference counts."""
+
+ NB_RUNS = 3
+
+ def run(self, result=None):
+ # python_message.py registers all Message classes to some pickle global
+ # registry, which makes the classes immortal.
+ # We save a copy of this registry, and reset it before we could references.
+ self._saved_pickle_registry = copyreg.dispatch_table.copy()
+
+ # Run the test twice, to warm up the instance attributes.
+ super(ReferenceLeakCheckerTestCase, self).run(result=result)
+ super(ReferenceLeakCheckerTestCase, self).run(result=result)
+
+ oldrefcount = 0
+ local_result = LocalTestResult(result)
+
+ refcount_deltas = []
+ for _ in range(self.NB_RUNS):
+ oldrefcount = self._getRefcounts()
+ super(ReferenceLeakCheckerTestCase, self).run(result=local_result)
+ newrefcount = self._getRefcounts()
+ refcount_deltas.append(newrefcount - oldrefcount)
+ print(refcount_deltas, self)
+
+ try:
+ self.assertEqual(refcount_deltas, [0] * self.NB_RUNS)
+ except Exception: # pylint: disable=broad-except
+ result.addError(self, sys.exc_info())
+
+ def _getRefcounts(self):
+ copyreg.dispatch_table.clear()
+ copyreg.dispatch_table.update(self._saved_pickle_registry)
+ # It is sometimes necessary to gc.collect() multiple times, to ensure
+ # that all objects can be collected.
+ gc.collect()
+ gc.collect()
+ gc.collect()
+ return sys.gettotalrefcount()
+
+
+if hasattr(sys, 'gettotalrefcount'):
+ BaseTestCase = ReferenceLeakCheckerTestCase
+ SkipReferenceLeakChecker = unittest.skip
+
+else:
+ # When PyDEBUG is not enabled, run the tests normally.
+ BaseTestCase = unittest.TestCase
+
+ def SkipReferenceLeakChecker(reason):
+ del reason # Don't skip, so don't need a reason.
+ def Same(func):
+ return func
+ return Same
+
+
diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py
index 0e38e0e9..ab481ab4 100755
--- a/python/google/protobuf/internal/text_format_test.py
+++ b/python/google/protobuf/internal/text_format_test.py
@@ -52,6 +52,7 @@ from google.protobuf import unittest_mset_pb2
from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
from google.protobuf.internal import api_implementation
+from google.protobuf.internal import any_test_pb2 as test_extend_any
from google.protobuf.internal import test_util
from google.protobuf.internal import message_set_extensions_pb2
from google.protobuf import descriptor_pool
@@ -684,6 +685,21 @@ class Proto2Tests(TextFormatBase):
self.assertEqual(23, message.message_set.Extensions[ext1].i)
self.assertEqual('foo', message.message_set.Extensions[ext2].str)
+ def testExtensionInsideAnyMessage(self):
+ message = test_extend_any.TestAny()
+ text = ('value {\n'
+ ' [type.googleapis.com/google.protobuf.internal.TestAny] {\n'
+ ' [google.protobuf.internal.TestAnyExtension1.extension1] {\n'
+ ' i: 10\n'
+ ' }\n'
+ ' }\n'
+ '}\n')
+ text_format.Merge(text, message, descriptor_pool=descriptor_pool.Default())
+ self.CompareToGoldenText(
+ text_format.MessageToString(
+ message, descriptor_pool=descriptor_pool.Default()),
+ text)
+
def testParseMessageByFieldNumber(self):
message = unittest_pb2.TestAllTypes()
text = ('34: 1\n' 'repeated_uint64: 2\n')
@@ -1184,7 +1200,8 @@ class TokenizerTest(unittest.TestCase):
'ID7 : "aa\\"bb"\n\n\n\n ID8: {A:inf B:-inf C:true D:false}\n'
'ID9: 22 ID10: -111111111111111111 ID11: -22\n'
'ID12: 2222222222222222222 ID13: 1.23456f ID14: 1.2e+2f '
- 'false_bool: 0 true_BOOL:t \n true_bool1: 1 false_BOOL1:f ')
+ 'false_bool: 0 true_BOOL:t \n true_bool1: 1 false_BOOL1:f '
+ 'False_bool: False True_bool: True')
tokenizer = text_format.Tokenizer(text.splitlines())
methods = [(tokenizer.ConsumeIdentifier, 'identifier1'), ':',
(tokenizer.ConsumeString, 'string1'),
@@ -1228,7 +1245,11 @@ class TokenizerTest(unittest.TestCase):
(tokenizer.ConsumeIdentifier, 'true_bool1'), ':',
(tokenizer.ConsumeBool, True),
(tokenizer.ConsumeIdentifier, 'false_BOOL1'), ':',
- (tokenizer.ConsumeBool, False)]
+ (tokenizer.ConsumeBool, False),
+ (tokenizer.ConsumeIdentifier, 'False_bool'), ':',
+ (tokenizer.ConsumeBool, False),
+ (tokenizer.ConsumeIdentifier, 'True_bool'), ':',
+ (tokenizer.ConsumeBool, True)]
i = 0
while not tokenizer.AtEnd():
diff --git a/python/google/protobuf/internal/unknown_fields_test.py b/python/google/protobuf/internal/unknown_fields_test.py
index 84073f1c..d614eaa8 100755
--- a/python/google/protobuf/internal/unknown_fields_test.py
+++ b/python/google/protobuf/internal/unknown_fields_test.py
@@ -47,16 +47,20 @@ from google.protobuf.internal import encoder
from google.protobuf.internal import message_set_extensions_pb2
from google.protobuf.internal import missing_enum_values_pb2
from google.protobuf.internal import test_util
+from google.protobuf.internal import testing_refleaks
from google.protobuf.internal import type_checkers
+BaseTestCase = testing_refleaks.BaseTestCase
+
+
def SkipIfCppImplementation(func):
return unittest.skipIf(
api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
'C++ implementation does not expose unknown fields to Python')(func)
-class UnknownFieldsTest(unittest.TestCase):
+class UnknownFieldsTest(BaseTestCase):
def setUp(self):
self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
@@ -140,7 +144,7 @@ class UnknownFieldsTest(unittest.TestCase):
b'', message.repeated_nested_message[0].SerializeToString())
-class UnknownFieldsAccessorsTest(unittest.TestCase):
+class UnknownFieldsAccessorsTest(BaseTestCase):
def setUp(self):
self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
@@ -149,21 +153,18 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
self.all_fields_data = self.all_fields.SerializeToString()
self.empty_message = unittest_pb2.TestEmptyMessage()
self.empty_message.ParseFromString(self.all_fields_data)
- if api_implementation.Type() != 'cpp':
- # _unknown_fields is an implementation detail.
- self.unknown_fields = self.empty_message._unknown_fields
- # All the tests that use GetField() check an implementation detail of the
- # Python implementation, which stores unknown fields as serialized strings.
- # These tests are skipped by the C++ implementation: it's enough to check that
- # the message is correctly serialized.
+ # GetUnknownField() checks a detail of the Python implementation, which stores
+ # unknown fields as serialized strings. It cannot be used by the C++
+ # implementation: it's enough to check that the message is correctly
+ # serialized.
- def GetField(self, name):
+ def GetUnknownField(self, name):
field_descriptor = self.descriptor.fields_by_name[name]
wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
field_tag = encoder.TagBytes(field_descriptor.number, wire_type)
result_dict = {}
- for tag_bytes, value in self.unknown_fields:
+ for tag_bytes, value in self.empty_message._unknown_fields:
if tag_bytes == field_tag:
decoder = unittest_pb2.TestAllTypes._decoders_by_tag[tag_bytes][0]
decoder(value, 0, len(value), self.all_fields, result_dict)
@@ -171,37 +172,37 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
@SkipIfCppImplementation
def testEnum(self):
- value = self.GetField('optional_nested_enum')
+ value = self.GetUnknownField('optional_nested_enum')
self.assertEqual(self.all_fields.optional_nested_enum, value)
@SkipIfCppImplementation
def testRepeatedEnum(self):
- value = self.GetField('repeated_nested_enum')
+ value = self.GetUnknownField('repeated_nested_enum')
self.assertEqual(self.all_fields.repeated_nested_enum, value)
@SkipIfCppImplementation
def testVarint(self):
- value = self.GetField('optional_int32')
+ value = self.GetUnknownField('optional_int32')
self.assertEqual(self.all_fields.optional_int32, value)
@SkipIfCppImplementation
def testFixed32(self):
- value = self.GetField('optional_fixed32')
+ value = self.GetUnknownField('optional_fixed32')
self.assertEqual(self.all_fields.optional_fixed32, value)
@SkipIfCppImplementation
def testFixed64(self):
- value = self.GetField('optional_fixed64')
+ value = self.GetUnknownField('optional_fixed64')
self.assertEqual(self.all_fields.optional_fixed64, value)
@SkipIfCppImplementation
def testLengthDelimited(self):
- value = self.GetField('optional_string')
+ value = self.GetUnknownField('optional_string')
self.assertEqual(self.all_fields.optional_string, value)
@SkipIfCppImplementation
def testGroup(self):
- value = self.GetField('optionalgroup')
+ value = self.GetUnknownField('optionalgroup')
self.assertEqual(self.all_fields.optionalgroup, value)
def testCopyFrom(self):
@@ -241,43 +242,41 @@ class UnknownFieldsAccessorsTest(unittest.TestCase):
self.assertEqual(message.SerializeToString(), self.all_fields_data)
-class UnknownEnumValuesTest(unittest.TestCase):
+class UnknownEnumValuesTest(BaseTestCase):
def setUp(self):
self.descriptor = missing_enum_values_pb2.TestEnumValues.DESCRIPTOR
self.message = missing_enum_values_pb2.TestEnumValues()
+ # TestEnumValues.ZERO = 0, but does not exist in the other NestedEnum.
self.message.optional_nested_enum = (
- missing_enum_values_pb2.TestEnumValues.ZERO)
+ missing_enum_values_pb2.TestEnumValues.ZERO)
self.message.repeated_nested_enum.extend([
- missing_enum_values_pb2.TestEnumValues.ZERO,
- missing_enum_values_pb2.TestEnumValues.ONE,
- ])
+ missing_enum_values_pb2.TestEnumValues.ZERO,
+ missing_enum_values_pb2.TestEnumValues.ONE,
+ ])
self.message.packed_nested_enum.extend([
- missing_enum_values_pb2.TestEnumValues.ZERO,
- missing_enum_values_pb2.TestEnumValues.ONE,
- ])
+ missing_enum_values_pb2.TestEnumValues.ZERO,
+ missing_enum_values_pb2.TestEnumValues.ONE,
+ ])
self.message_data = self.message.SerializeToString()
self.missing_message = missing_enum_values_pb2.TestMissingEnumValues()
self.missing_message.ParseFromString(self.message_data)
- if api_implementation.Type() != 'cpp':
- # _unknown_fields is an implementation detail.
- self.unknown_fields = self.missing_message._unknown_fields
- # All the tests that use GetField() check an implementation detail of the
- # Python implementation, which stores unknown fields as serialized strings.
- # These tests are skipped by the C++ implementation: it's enough to check that
- # the message is correctly serialized.
+ # GetUnknownField() checks a detail of the Python implementation, which stores
+ # unknown fields as serialized strings. It cannot be used by the C++
+ # implementation: it's enough to check that the message is correctly
+ # serialized.
- def GetField(self, name):
+ def GetUnknownField(self, name):
field_descriptor = self.descriptor.fields_by_name[name]
wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type]
field_tag = encoder.TagBytes(field_descriptor.number, wire_type)
result_dict = {}
- for tag_bytes, value in self.unknown_fields:
+ for tag_bytes, value in self.missing_message._unknown_fields:
if tag_bytes == field_tag:
decoder = missing_enum_values_pb2.TestEnumValues._decoders_by_tag[
- tag_bytes][0]
+ tag_bytes][0]
decoder(value, 0, len(value), self.message, result_dict)
return result_dict[field_descriptor]
@@ -294,21 +293,39 @@ class UnknownEnumValuesTest(unittest.TestCase):
# default value.
self.assertEqual(missing.optional_nested_enum, 0)
- @SkipIfCppImplementation
def testUnknownEnumValue(self):
+ if api_implementation.Type() == 'cpp':
+ # The CPP implementation of protos (wrongly) allows unknown enum values
+ # for proto2.
+ self.assertTrue(self.missing_message.HasField('optional_nested_enum'))
+ self.assertEqual(self.message.optional_nested_enum,
+ self.missing_message.optional_nested_enum)
+ else:
+ # On the other hand, the Python implementation considers unknown values
+ # as unknown fields. This is the correct behavior.
+ self.assertFalse(self.missing_message.HasField('optional_nested_enum'))
+ value = self.GetUnknownField('optional_nested_enum')
+ self.assertEqual(self.message.optional_nested_enum, value)
+ self.missing_message.ClearField('optional_nested_enum')
self.assertFalse(self.missing_message.HasField('optional_nested_enum'))
- value = self.GetField('optional_nested_enum')
- self.assertEqual(self.message.optional_nested_enum, value)
- @SkipIfCppImplementation
def testUnknownRepeatedEnumValue(self):
- value = self.GetField('repeated_nested_enum')
- self.assertEqual(self.message.repeated_nested_enum, value)
+ if api_implementation.Type() == 'cpp':
+ # For repeated enums, both implementations agree.
+ self.assertEqual([], self.missing_message.repeated_nested_enum)
+ else:
+ self.assertEqual([], self.missing_message.repeated_nested_enum)
+ value = self.GetUnknownField('repeated_nested_enum')
+ self.assertEqual(self.message.repeated_nested_enum, value)
- @SkipIfCppImplementation
def testUnknownPackedEnumValue(self):
- value = self.GetField('packed_nested_enum')
- self.assertEqual(self.message.packed_nested_enum, value)
+ if api_implementation.Type() == 'cpp':
+ # For repeated enums, both implementations agree.
+ self.assertEqual([], self.missing_message.packed_nested_enum)
+ else:
+ self.assertEqual([], self.missing_message.packed_nested_enum)
+ value = self.GetUnknownField('packed_nested_enum')
+ self.assertEqual(self.message.packed_nested_enum, value)
def testRoundTrip(self):
new_message = missing_enum_values_pb2.TestEnumValues()
diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py
index 7c5dffd0..d631abee 100644
--- a/python/google/protobuf/internal/well_known_types.py
+++ b/python/google/protobuf/internal/well_known_types.py
@@ -53,6 +53,7 @@ _NANOS_PER_MICROSECOND = 1000
_MILLIS_PER_SECOND = 1000
_MICROS_PER_SECOND = 1000000
_SECONDS_PER_DAY = 24 * 3600
+_DURATION_SECONDS_MAX = 315576000000
class Error(Exception):
@@ -247,6 +248,7 @@ class Duration(object):
represent the exact Duration value. For example: "1s", "1.010s",
"1.000000100s", "-3.100s"
"""
+ _CheckDurationValid(self.seconds, self.nanos)
if self.seconds < 0 or self.nanos < 0:
result = '-'
seconds = - self.seconds + int((0 - self.nanos) // 1e9)
@@ -286,14 +288,17 @@ class Duration(object):
try:
pos = value.find('.')
if pos == -1:
- self.seconds = int(value[:-1])
- self.nanos = 0
+ seconds = int(value[:-1])
+ nanos = 0
else:
- self.seconds = int(value[:pos])
+ seconds = int(value[:pos])
if value[0] == '-':
- self.nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))
+ nanos = int(round(float('-0{0}'.format(value[pos: -1])) *1e9))
else:
- self.nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))
+ nanos = int(round(float('0{0}'.format(value[pos: -1])) *1e9))
+ _CheckDurationValid(seconds, nanos)
+ self.seconds = seconds
+ self.nanos = nanos
except ValueError:
raise ParseError(
'Couldn\'t parse duration: {0}.'.format(value))
@@ -359,6 +364,17 @@ class Duration(object):
self.nanos = nanos
+def _CheckDurationValid(seconds, nanos):
+ if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX:
+ raise Error(
+ 'Duration is not valid: Seconds {0} must be in range '
+ '[-315576000000, 315576000000].'.format(seconds))
+ if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND:
+ raise Error(
+ 'Duration is not valid: Nanos {0} must be in range '
+ '[-999999999, 999999999].'.format(nanos))
+
+
def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
@@ -379,13 +395,16 @@ class FieldMask(object):
def ToJsonString(self):
"""Converts FieldMask to string according to proto3 JSON spec."""
- return ','.join(self.paths)
+ camelcase_paths = []
+ for path in self.paths:
+ camelcase_paths.append(_SnakeCaseToCamelCase(path))
+ return ','.join(camelcase_paths)
def FromJsonString(self, value):
"""Converts string to FieldMask according to proto3 JSON spec."""
self.Clear()
for path in value.split(','):
- self.paths.append(path)
+ self.paths.append(_CamelCaseToSnakeCase(path))
def IsValidForDescriptor(self, message_descriptor):
"""Checks whether the FieldMask is valid for Message Descriptor."""
@@ -472,6 +491,48 @@ def _CheckFieldMaskMessage(message):
message_descriptor.full_name))
+def _SnakeCaseToCamelCase(path_name):
+ """Converts a path name from snake_case to camelCase."""
+ result = []
+ after_underscore = False
+ for c in path_name:
+ if c.isupper():
+ raise Error('Fail to print FieldMask to Json string: Path name '
+ '{0} must not contain uppercase letters.'.format(path_name))
+ if after_underscore:
+ if c.islower():
+ result.append(c.upper())
+ after_underscore = False
+ else:
+ raise Error('Fail to print FieldMask to Json string: The '
+ 'character after a "_" must be a lowercase letter '
+ 'in path name {0}.'.format(path_name))
+ elif c == '_':
+ after_underscore = True
+ else:
+ result += c
+
+ if after_underscore:
+ raise Error('Fail to print FieldMask to Json string: Trailing "_" '
+ 'in path name {0}.'.format(path_name))
+ return ''.join(result)
+
+
+def _CamelCaseToSnakeCase(path_name):
+ """Converts a field name from camelCase to snake_case."""
+ result = []
+ for c in path_name:
+ if c == '_':
+ raise ParseError('Fail to parse FieldMask: Path name '
+ '{0} must not contain "_"s.'.format(path_name))
+ if c.isupper():
+ result += '_'
+ result += c.lower()
+ else:
+ result += c
+ return ''.join(result)
+
+
class _FieldMaskTree(object):
"""Represents a FieldMask in a tree structure.
diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py
index 2f32ac99..077f630f 100644
--- a/python/google/protobuf/internal/well_known_types_test.py
+++ b/python/google/protobuf/internal/well_known_types_test.py
@@ -303,6 +303,25 @@ class TimeUtilTest(TimeUtilTestBase):
well_known_types.ParseError,
'Couldn\'t parse duration: 1...2s.',
message.FromJsonString, '1...2s')
+ text = '-315576000001.000000000s'
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ r'Duration is not valid\: Seconds -315576000001 must be in range'
+ r' \[-315576000000\, 315576000000\].',
+ message.FromJsonString, text)
+ text = '315576000001.000000000s'
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ r'Duration is not valid\: Seconds 315576000001 must be in range'
+ r' \[-315576000000\, 315576000000\].',
+ message.FromJsonString, text)
+ message.seconds = -315576000001
+ message.nanos = 0
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ r'Duration is not valid\: Seconds -315576000001 must be in range'
+ r' \[-315576000000\, 315576000000\].',
+ message.ToJsonString)
class FieldMaskTest(unittest.TestCase):
@@ -322,6 +341,20 @@ class FieldMaskTest(unittest.TestCase):
mask.FromJsonString('foo,bar')
self.assertEqual(['foo', 'bar'], mask.paths)
+ # Test camel case
+ mask.Clear()
+ mask.paths.append('foo_bar')
+ self.assertEqual('fooBar', mask.ToJsonString())
+ mask.paths.append('bar_quz')
+ self.assertEqual('fooBar,barQuz', mask.ToJsonString())
+
+ mask.FromJsonString('')
+ self.assertEqual('', mask.ToJsonString())
+ mask.FromJsonString('fooBar')
+ self.assertEqual(['foo_bar'], mask.paths)
+ mask.FromJsonString('fooBar,barQuz')
+ self.assertEqual(['foo_bar', 'bar_quz'], mask.paths)
+
def testDescriptorToFieldMask(self):
mask = field_mask_pb2.FieldMask()
msg_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
@@ -502,17 +535,68 @@ class FieldMaskTest(unittest.TestCase):
nested_src.payload.repeated_int32.append(1234)
nested_dst.payload.repeated_int32.append(5678)
# Repeated fields will be appended by default.
- mask.FromJsonString('payload.repeated_int32')
+ mask.FromJsonString('payload.repeatedInt32')
mask.MergeMessage(nested_src, nested_dst)
self.assertEqual(2, len(nested_dst.payload.repeated_int32))
self.assertEqual(5678, nested_dst.payload.repeated_int32[0])
self.assertEqual(1234, nested_dst.payload.repeated_int32[1])
# Change the behavior to replace repeated fields.
- mask.FromJsonString('payload.repeated_int32')
+ mask.FromJsonString('payload.repeatedInt32')
mask.MergeMessage(nested_src, nested_dst, False, True)
self.assertEqual(1, len(nested_dst.payload.repeated_int32))
self.assertEqual(1234, nested_dst.payload.repeated_int32[0])
+ def testSnakeCaseToCamelCase(self):
+ self.assertEqual('fooBar',
+ well_known_types._SnakeCaseToCamelCase('foo_bar'))
+ self.assertEqual('FooBar',
+ well_known_types._SnakeCaseToCamelCase('_foo_bar'))
+ self.assertEqual('foo3Bar',
+ well_known_types._SnakeCaseToCamelCase('foo3_bar'))
+
+ # No uppercase letter is allowed.
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ 'Fail to print FieldMask to Json string: Path name Foo must '
+ 'not contain uppercase letters.',
+ well_known_types._SnakeCaseToCamelCase,
+ 'Foo')
+ # Any character after a "_" must be a lowercase letter.
+ # 1. "_" cannot be followed by another "_".
+ # 2. "_" cannot be followed by a digit.
+ # 3. "_" cannot appear as the last character.
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ 'Fail to print FieldMask to Json string: The character after a '
+ '"_" must be a lowercase letter in path name foo__bar.',
+ well_known_types._SnakeCaseToCamelCase,
+ 'foo__bar')
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ 'Fail to print FieldMask to Json string: The character after a '
+ '"_" must be a lowercase letter in path name foo_3bar.',
+ well_known_types._SnakeCaseToCamelCase,
+ 'foo_3bar')
+ self.assertRaisesRegexp(
+ well_known_types.Error,
+ 'Fail to print FieldMask to Json string: Trailing "_" in path '
+ 'name foo_bar_.',
+ well_known_types._SnakeCaseToCamelCase,
+ 'foo_bar_')
+
+ def testCamelCaseToSnakeCase(self):
+ self.assertEqual('foo_bar',
+ well_known_types._CamelCaseToSnakeCase('fooBar'))
+ self.assertEqual('_foo_bar',
+ well_known_types._CamelCaseToSnakeCase('FooBar'))
+ self.assertEqual('foo3_bar',
+ well_known_types._CamelCaseToSnakeCase('foo3Bar'))
+ self.assertRaisesRegexp(
+ well_known_types.ParseError,
+ 'Fail to parse FieldMask: Path name foo_bar must not contain "_"s.',
+ well_known_types._CamelCaseToSnakeCase,
+ 'foo_bar')
+
class StructTest(unittest.TestCase):
@@ -529,52 +613,52 @@ class StructTest(unittest.TestCase):
struct_list.add_struct()['subkey2'] = 9
self.assertTrue(isinstance(struct, well_known_types.Struct))
- self.assertEquals(5, struct['key1'])
- self.assertEquals('abc', struct['key2'])
+ self.assertEqual(5, struct['key1'])
+ self.assertEqual('abc', struct['key2'])
self.assertIs(True, struct['key3'])
- self.assertEquals(11, struct['key4']['subkey'])
+ self.assertEqual(11, struct['key4']['subkey'])
inner_struct = struct_class()
inner_struct['subkey2'] = 9
- self.assertEquals([6, 'seven', True, False, None, inner_struct],
- list(struct['key5'].items()))
+ self.assertEqual([6, 'seven', True, False, None, inner_struct],
+ list(struct['key5'].items()))
serialized = struct.SerializeToString()
struct2 = struct_pb2.Struct()
struct2.ParseFromString(serialized)
- self.assertEquals(struct, struct2)
+ self.assertEqual(struct, struct2)
self.assertTrue(isinstance(struct2, well_known_types.Struct))
- self.assertEquals(5, struct2['key1'])
- self.assertEquals('abc', struct2['key2'])
+ self.assertEqual(5, struct2['key1'])
+ self.assertEqual('abc', struct2['key2'])
self.assertIs(True, struct2['key3'])
- self.assertEquals(11, struct2['key4']['subkey'])
- self.assertEquals([6, 'seven', True, False, None, inner_struct],
- list(struct2['key5'].items()))
+ self.assertEqual(11, struct2['key4']['subkey'])
+ self.assertEqual([6, 'seven', True, False, None, inner_struct],
+ list(struct2['key5'].items()))
struct_list = struct2['key5']
- self.assertEquals(6, struct_list[0])
- self.assertEquals('seven', struct_list[1])
- self.assertEquals(True, struct_list[2])
- self.assertEquals(False, struct_list[3])
- self.assertEquals(None, struct_list[4])
- self.assertEquals(inner_struct, struct_list[5])
+ self.assertEqual(6, struct_list[0])
+ self.assertEqual('seven', struct_list[1])
+ self.assertEqual(True, struct_list[2])
+ self.assertEqual(False, struct_list[3])
+ self.assertEqual(None, struct_list[4])
+ self.assertEqual(inner_struct, struct_list[5])
struct_list[1] = 7
- self.assertEquals(7, struct_list[1])
+ self.assertEqual(7, struct_list[1])
struct_list.add_list().extend([1, 'two', True, False, None])
- self.assertEquals([1, 'two', True, False, None],
- list(struct_list[6].items()))
+ self.assertEqual([1, 'two', True, False, None],
+ list(struct_list[6].items()))
text_serialized = str(struct)
struct3 = struct_pb2.Struct()
text_format.Merge(text_serialized, struct3)
- self.assertEquals(struct, struct3)
+ self.assertEqual(struct, struct3)
struct.get_or_create_struct('key3')['replace'] = 12
- self.assertEquals(12, struct['key3']['replace'])
+ self.assertEqual(12, struct['key3']['replace'])
class AnyTest(unittest.TestCase):
diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py
index bb6a1998..c42371d0 100644
--- a/python/google/protobuf/json_format.py
+++ b/python/google/protobuf/json_format.py
@@ -86,7 +86,9 @@ class ParseError(Error):
"""Thrown in case of parsing error."""
-def MessageToJson(message, including_default_value_fields=False):
+def MessageToJson(message,
+ including_default_value_fields=False,
+ preserving_proto_field_name=False):
"""Converts protobuf message to JSON format.
Args:
@@ -95,14 +97,42 @@ def MessageToJson(message, including_default_value_fields=False):
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
+ 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.
Returns:
A string containing the JSON formatted protocol buffer message.
"""
- printer = _Printer(including_default_value_fields)
+ printer = _Printer(including_default_value_fields,
+ preserving_proto_field_name)
return printer.ToJsonString(message)
+def MessageToDict(message,
+ including_default_value_fields=False,
+ preserving_proto_field_name=False):
+ """Converts protobuf message to a JSON dictionary.
+
+ Args:
+ message: The protocol buffers message instance to serialize.
+ including_default_value_fields: If True, singular primitive fields,
+ repeated fields, and map fields will always be serialized. If
+ False, only serialize non-empty fields. Singular message fields
+ and oneof fields are not affected by this option.
+ 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.
+
+ Returns:
+ A dict representation of the JSON formatted protocol buffer message.
+ """
+ printer = _Printer(including_default_value_fields,
+ preserving_proto_field_name)
+ # pylint: disable=protected-access
+ return printer._MessageToJsonObject(message)
+
+
def _IsMapEntry(field):
return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
field.message_type.has_options and
@@ -113,8 +143,10 @@ class _Printer(object):
"""JSON format printer for protocol message."""
def __init__(self,
- including_default_value_fields=False):
+ including_default_value_fields=False,
+ preserving_proto_field_name=False):
self.including_default_value_fields = including_default_value_fields
+ self.preserving_proto_field_name = preserving_proto_field_name
def ToJsonString(self, message):
js = self._MessageToJsonObject(message)
@@ -137,7 +169,10 @@ class _Printer(object):
try:
for field, value in fields:
- name = field.camelcase_name
+ if self.preserving_proto_field_name:
+ name = field.name
+ else:
+ name = field.json_name
if _IsMapEntry(field):
# Convert a map field.
v_field = field.message_type.fields_by_name['value']
@@ -169,7 +204,10 @@ class _Printer(object):
field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or
field.containing_oneof):
continue
- name = field.camelcase_name
+ if self.preserving_proto_field_name:
+ name = field.name
+ else:
+ name = field.json_name
if name in js:
# Skip the field which has been serailized already.
continue
@@ -310,7 +348,7 @@ def Parse(text, message, ignore_unknown_fields=False):
Args:
text: Message JSON representation.
- message: A protocol beffer message to merge into.
+ message: A protocol buffer message to merge into.
ignore_unknown_fields: If True, do not raise errors for unknown fields.
Returns:
@@ -328,8 +366,22 @@ def Parse(text, message, ignore_unknown_fields=False):
js = json.loads(text, object_pairs_hook=_DuplicateChecker)
except ValueError as e:
raise ParseError('Failed to load JSON: {0}.'.format(str(e)))
+ return ParseDict(js, message, ignore_unknown_fields)
+
+
+def ParseDict(js_dict, message, ignore_unknown_fields=False):
+ """Parses a JSON dictionary representation into a message.
+
+ Args:
+ js_dict: Dict representation of a JSON message.
+ message: A protocol buffer message to merge into.
+ ignore_unknown_fields: If True, do not raise errors for unknown fields.
+
+ Returns:
+ The same message passed as argument.
+ """
parser = _Parser(ignore_unknown_fields)
- parser.ConvertMessage(js, message)
+ parser.ConvertMessage(js_dict, message)
return message
@@ -374,9 +426,13 @@ class _Parser(object):
"""
names = []
message_descriptor = message.DESCRIPTOR
+ fields_by_json_name = dict((f.json_name, f)
+ for f in message_descriptor.fields)
for name in js:
try:
- field = message_descriptor.fields_by_camelcase_name.get(name, None)
+ field = fields_by_json_name.get(name, None)
+ if not field:
+ field = message_descriptor.fields_by_name.get(name, None)
if not field:
if self.ignore_unknown_fields:
continue
@@ -399,7 +455,12 @@ class _Parser(object):
value = js[name]
if value is None:
- message.ClearField(field.name)
+ if (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE
+ and field.message_type.full_name == 'google.protobuf.Value'):
+ sub_message = getattr(message, field.name)
+ sub_message.null_value = 0
+ else:
+ message.ClearField(field.name)
continue
# Parse field value.
@@ -431,6 +492,7 @@ class _Parser(object):
_ConvertScalarFieldValue(item, field))
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
sub_message = getattr(message, field.name)
+ sub_message.SetInParent()
self.ConvertMessage(value, sub_message)
else:
setattr(message, field.name, _ConvertScalarFieldValue(value, field))
@@ -574,10 +636,15 @@ def _ConvertScalarFieldValue(value, field, require_str=False):
# Convert an enum value.
enum_value = field.enum_type.values_by_name.get(value, None)
if enum_value is None:
- raise ParseError(
- 'Enum value must be a string literal with double quotes. '
- 'Type "{0}" has no value named {1}.'.format(
- field.enum_type.full_name, value))
+ try:
+ number = int(value)
+ enum_value = field.enum_type.values_by_number.get(number, None)
+ except ValueError:
+ raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
+ value, field.enum_type.full_name))
+ if enum_value is None:
+ raise ParseError('Invalid enum value {0} for enum type {1}.'.format(
+ value, field.enum_type.full_name))
return enum_value.number
@@ -593,7 +660,7 @@ def _ConvertInteger(value):
Raises:
ParseError: If an integer couldn't be consumed.
"""
- if isinstance(value, float):
+ if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
if isinstance(value, six.text_type) and value.find(' ') != -1:
diff --git a/python/google/protobuf/message.py b/python/google/protobuf/message.py
index 606f735f..aab250e4 100755
--- a/python/google/protobuf/message.py
+++ b/python/google/protobuf/message.py
@@ -225,10 +225,11 @@ class Message(object):
# """
def ListFields(self):
"""Returns a list of (FieldDescriptor, value) tuples for all
- fields in the message which are not empty. A singular field is non-empty
- if HasField() would return true, and a repeated field is non-empty if
- it contains at least one element. The fields are ordered by field
- number"""
+ fields in the message which are not empty. A message field is
+ non-empty if HasField() would return true. A singular primitive field
+ is non-empty if HasField() would return true in proto2 or it is non zero
+ in proto3. A repeated field is non-empty if it contains at least one
+ element. The fields are ordered by field number"""
raise NotImplementedError
def HasField(self, field_name):
diff --git a/python/google/protobuf/message_factory.py b/python/google/protobuf/message_factory.py
index 1b059d13..8ab1c513 100644
--- a/python/google/protobuf/message_factory.py
+++ b/python/google/protobuf/message_factory.py
@@ -103,13 +103,8 @@ class MessageFactory(object):
result = {}
for file_name in files:
file_desc = self.pool.FindFileByName(file_name)
- for name, msg in file_desc.message_types_by_name.items():
- if file_desc.package:
- full_name = '.'.join([file_desc.package, name])
- else:
- full_name = msg.name
- result[full_name] = self.GetPrototype(
- self.pool.FindMessageTypeByName(full_name))
+ for desc in file_desc.message_types_by_name.values():
+ result[desc.full_name] = self.GetPrototype(desc)
# While the extension FieldDescriptors are created by the descriptor pool,
# the python classes created in the factory need them to be registered
@@ -120,7 +115,7 @@ class MessageFactory(object):
# ignore the registration if the original was the same, or raise
# an error if they were different.
- for name, extension in file_desc.extensions_by_name.items():
+ for extension in file_desc.extensions_by_name.values():
if extension.containing_type.full_name not in self._classes:
self.GetPrototype(extension.containing_type)
extended_class = self._classes[extension.containing_type.full_name]
diff --git a/python/google/protobuf/pyext/descriptor.cc b/python/google/protobuf/pyext/descriptor.cc
index e6ef5ef5..924ae0b9 100644
--- a/python/google/protobuf/pyext/descriptor.cc
+++ b/python/google/protobuf/pyext/descriptor.cc
@@ -41,6 +41,7 @@
#include <google/protobuf/pyext/descriptor_containers.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#if PY_MAJOR_VERSION >= 3
@@ -204,8 +205,9 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
// read-only instance.
const Message& options(descriptor->options());
const Descriptor *message_type = options.GetDescriptor();
- CMessageClass* message_class(
- cdescriptor_pool::GetMessageClass(pool, message_type));
+ PyMessageFactory* message_factory = pool->py_message_factory;
+ CMessageClass* message_class = message_factory::GetMessageClass(
+ 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
@@ -213,7 +215,9 @@ static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) {
// the chances of successfully parsing the options.
PyErr_Clear();
pool = GetDefaultDescriptorPool();
- message_class = cdescriptor_pool::GetMessageClass(pool, message_type);
+ 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",
@@ -243,7 +247,7 @@ 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, pool->message_factory);
+ input.SetExtensionRegistry(pool->pool, message_factory->message_factory);
bool success = cmsg->message->MergePartialFromCodedStream(&input);
if (!success) {
PyErr_Format(PyExc_ValueError, "Error parsing Options message");
@@ -439,8 +443,9 @@ static PyObject* GetConcreteClass(PyBaseDescriptor* self, void *closure) {
// which contains this descriptor.
// This might not be the one you expect! For example the returned object does
// not know about extensions defined in a custom pool.
- CMessageClass* concrete_class(cdescriptor_pool::GetMessageClass(
- GetDescriptorPool_FromPool(_GetDescriptor(self)->file()->pool()),
+ CMessageClass* concrete_class(message_factory::GetMessageClass(
+ GetDescriptorPool_FromPool(
+ _GetDescriptor(self)->file()->pool())->py_message_factory,
_GetDescriptor(self)));
Py_XINCREF(concrete_class);
return concrete_class->AsPyObject();
@@ -699,6 +704,10 @@ static PyObject* GetCamelcaseName(PyBaseDescriptor* self, void *closure) {
return PyString_FromCppString(_GetDescriptor(self)->camelcase_name());
}
+static PyObject* GetJsonName(PyBaseDescriptor* self, void *closure) {
+ return PyString_FromCppString(_GetDescriptor(self)->json_name());
+}
+
static PyObject* GetType(PyBaseDescriptor *self, void *closure) {
return PyInt_FromLong(_GetDescriptor(self)->type());
}
@@ -888,6 +897,7 @@ static PyGetSetDef Getters[] = {
{ "full_name", (getter)GetFullName, NULL, "Full name"},
{ "name", (getter)GetName, NULL, "Unqualified name"},
{ "camelcase_name", (getter)GetCamelcaseName, NULL, "Camelcase name"},
+ { "json_name", (getter)GetJsonName, NULL, "Json name"},
{ "type", (getter)GetType, NULL, "C++ Type"},
{ "cpp_type", (getter)GetCppType, NULL, "C++ Type"},
{ "label", (getter)GetLabel, NULL, "Label"},
diff --git a/python/google/protobuf/pyext/descriptor_pool.cc b/python/google/protobuf/pyext/descriptor_pool.cc
index cfd98690..a42e5431 100644
--- a/python/google/protobuf/pyext/descriptor_pool.cc
+++ b/python/google/protobuf/pyext/descriptor_pool.cc
@@ -33,11 +33,11 @@
#include <Python.h>
#include <google/protobuf/descriptor.pb.h>
-#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/descriptor_database.h>
#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#if PY_MAJOR_VERSION >= 3
@@ -73,18 +73,16 @@ static PyDescriptorPool* _CreateDescriptorPool() {
cpool->underlay = NULL;
cpool->database = NULL;
- DynamicMessageFactory* message_factory = new DynamicMessageFactory();
- // This option might be the default some day.
- message_factory->SetDelegateToGeneratedFactory(true);
- cpool->message_factory = message_factory;
-
- // TODO(amauryfa): Rewrite the SymbolDatabase in C so that it uses the same
- // storage.
- cpool->classes_by_descriptor =
- new PyDescriptorPool::ClassesByMessageMap();
cpool->descriptor_options =
new hash_map<const void*, PyObject *>();
+ cpool->py_message_factory = message_factory::NewMessageFactory(
+ &PyMessageFactory_Type, cpool);
+ if (cpool->py_message_factory == NULL) {
+ Py_DECREF(cpool);
+ return NULL;
+ }
+
return cpool;
}
@@ -151,20 +149,14 @@ static PyObject* New(PyTypeObject* type,
}
static void Dealloc(PyDescriptorPool* self) {
- typedef PyDescriptorPool::ClassesByMessageMap::iterator iterator;
descriptor_pool_map.erase(self->pool);
- for (iterator it = self->classes_by_descriptor->begin();
- it != self->classes_by_descriptor->end(); ++it) {
- Py_DECREF(it->second);
- }
- delete self->classes_by_descriptor;
+ Py_CLEAR(self->py_message_factory);
for (hash_map<const void*, PyObject*>::iterator it =
self->descriptor_options->begin();
it != self->descriptor_options->end(); ++it) {
Py_DECREF(it->second);
}
delete self->descriptor_options;
- delete self->message_factory;
delete self->database;
delete self->pool;
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
@@ -188,35 +180,8 @@ PyObject* FindMessageByName(PyDescriptorPool* self, PyObject* arg) {
return PyMessageDescriptor_FromDescriptor(message_descriptor);
}
-// Add a message class to our database.
-int RegisterMessageClass(PyDescriptorPool* self,
- const Descriptor* message_descriptor,
- CMessageClass* message_class) {
- Py_INCREF(message_class);
- typedef PyDescriptorPool::ClassesByMessageMap::iterator iterator;
- std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
- std::make_pair(message_descriptor, message_class));
- if (!ret.second) {
- // Update case: DECREF the previous value.
- Py_DECREF(ret.first->second);
- ret.first->second = message_class;
- }
- return 0;
-}
-// Retrieve the message class added to our database.
-CMessageClass* GetMessageClass(PyDescriptorPool* self,
- const Descriptor* message_descriptor) {
- typedef PyDescriptorPool::ClassesByMessageMap::iterator iterator;
- iterator ret = self->classes_by_descriptor->find(message_descriptor);
- if (ret == self->classes_by_descriptor->end()) {
- PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
- message_descriptor->full_name().c_str());
- return NULL;
- } else {
- return ret->second;
- }
-}
+
PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) {
Py_ssize_t name_size;
@@ -228,11 +193,9 @@ PyObject* FindFileByName(PyDescriptorPool* self, PyObject* arg) {
const FileDescriptor* file_descriptor =
self->pool->FindFileByName(string(name, name_size));
if (file_descriptor == NULL) {
- PyErr_Format(PyExc_KeyError, "Couldn't find file %.200s",
- name);
+ PyErr_Format(PyExc_KeyError, "Couldn't find file %.200s", name);
return NULL;
}
-
return PyFileDescriptor_FromDescriptor(file_descriptor);
}
diff --git a/python/google/protobuf/pyext/descriptor_pool.h b/python/google/protobuf/pyext/descriptor_pool.h
index 2a42c112..c4d7d403 100644
--- a/python/google/protobuf/pyext/descriptor_pool.h
+++ b/python/google/protobuf/pyext/descriptor_pool.h
@@ -38,10 +38,10 @@
namespace google {
namespace protobuf {
-class MessageFactory;
-
namespace python {
+struct PyMessageFactory;
+
// The (meta) type of all Messages classes.
struct CMessageClass;
@@ -69,20 +69,10 @@ typedef struct PyDescriptorPool {
// This pointer is owned.
const DescriptorDatabase* database;
- // DynamicMessageFactory used to create C++ instances of messages.
- // This object cache the descriptors that were used, so the DescriptorPool
- // needs to get rid of it before it can delete itself.
- //
- // Note: A C++ MessageFactory is different from the Python MessageFactory.
- // The C++ one creates messages, when the Python one creates classes.
- MessageFactory* message_factory;
-
- // Make our own mapping to retrieve Python classes from C++ descriptors.
- //
- // Descriptor pointers stored here are owned by the DescriptorPool above.
- // Python references to classes are owned by this PyDescriptorPool.
- typedef hash_map<const Descriptor*, CMessageClass*> ClassesByMessageMap;
- ClassesByMessageMap* classes_by_descriptor;
+ // The preferred MessageFactory to be used by descriptors.
+ // TODO(amauryfa): Don't create the Factory from the DescriptorPool, but
+ // use the one passed while creating message classes. And remove this member.
+ PyMessageFactory* py_message_factory;
// Cache the options for any kind of descriptor.
// Descriptor pointers are owned by the DescriptorPool above.
@@ -100,19 +90,6 @@ namespace cdescriptor_pool {
const Descriptor* FindMessageTypeByName(PyDescriptorPool* self,
const string& name);
-// Registers a new Python class for the given message descriptor.
-// On error, returns -1 with a Python exception set.
-int RegisterMessageClass(PyDescriptorPool* self,
- const Descriptor* message_descriptor,
- CMessageClass* message_class);
-
-// Retrieves the Python class registered with the given message descriptor.
-//
-// Returns a *borrowed* reference if found, otherwise returns NULL with an
-// exception set.
-CMessageClass* GetMessageClass(PyDescriptorPool* self,
- const Descriptor* message_descriptor);
-
// The functions below are also exposed as methods of the DescriptorPool type.
// Looks up a message by name. Returns a PyMessageDescriptor corresponding to
diff --git a/python/google/protobuf/pyext/extension_dict.cc b/python/google/protobuf/pyext/extension_dict.cc
index 21bbb8c2..dbb7bca0 100644
--- a/python/google/protobuf/pyext/extension_dict.cc
+++ b/python/google/protobuf/pyext/extension_dict.cc
@@ -39,8 +39,8 @@
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/message.h>
#include <google/protobuf/pyext/descriptor.h>
-#include <google/protobuf/pyext/descriptor_pool.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/repeated_composite_container.h>
#include <google/protobuf/pyext/repeated_scalar_container.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
@@ -60,35 +60,6 @@ PyObject* len(ExtensionDict* self) {
#endif
}
-// TODO(tibell): Use VisitCompositeField.
-int ReleaseExtension(ExtensionDict* self,
- PyObject* extension,
- const FieldDescriptor* descriptor) {
- if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
- if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- if (repeated_composite_container::Release(
- reinterpret_cast<RepeatedCompositeContainer*>(
- extension)) < 0) {
- return -1;
- }
- } else {
- if (repeated_scalar_container::Release(
- reinterpret_cast<RepeatedScalarContainer*>(
- extension)) < 0) {
- return -1;
- }
- }
- } else if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- if (cmessage::ReleaseSubMessage(
- self->parent, descriptor,
- reinterpret_cast<CMessage*>(extension)) < 0) {
- return -1;
- }
- }
-
- return 0;
-}
-
PyObject* subscript(ExtensionDict* self, PyObject* key) {
const FieldDescriptor* descriptor = cmessage::GetExtensionDescriptor(key);
if (descriptor == NULL) {
@@ -130,8 +101,8 @@ PyObject* subscript(ExtensionDict* self, PyObject* key) {
if (descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- CMessageClass* message_class = cdescriptor_pool::GetMessageClass(
- cmessage::GetDescriptorPoolForMessage(self->parent),
+ CMessageClass* message_class = message_factory::GetMessageClass(
+ cmessage::GetFactoryForMessage(self->parent),
descriptor->message_type());
if (message_class == NULL) {
return NULL;
@@ -183,47 +154,6 @@ int ass_subscript(ExtensionDict* self, PyObject* key, PyObject* value) {
return 0;
}
-PyObject* ClearExtension(ExtensionDict* self, PyObject* extension) {
- const FieldDescriptor* descriptor =
- cmessage::GetExtensionDescriptor(extension);
- if (descriptor == NULL) {
- return NULL;
- }
- PyObject* value = PyDict_GetItem(self->values, extension);
- if (self->parent) {
- if (value != NULL) {
- if (ReleaseExtension(self, value, descriptor) < 0) {
- return NULL;
- }
- }
- if (ScopedPyObjectPtr(cmessage::ClearFieldByDescriptor(
- self->parent, descriptor)) == NULL) {
- return NULL;
- }
- }
- if (PyDict_DelItem(self->values, extension) < 0) {
- PyErr_Clear();
- }
- Py_RETURN_NONE;
-}
-
-PyObject* HasExtension(ExtensionDict* self, PyObject* extension) {
- const FieldDescriptor* descriptor =
- cmessage::GetExtensionDescriptor(extension);
- if (descriptor == NULL) {
- return NULL;
- }
- if (self->parent) {
- return cmessage::HasFieldByDescriptor(self->parent, descriptor);
- } else {
- int exists = PyDict_Contains(self->values, extension);
- if (exists < 0) {
- return NULL;
- }
- return PyBool_FromLong(exists);
- }
-}
-
PyObject* _FindExtensionByName(ExtensionDict* self, PyObject* name) {
ScopedPyObjectPtr extensions_by_name(PyObject_GetAttrString(
reinterpret_cast<PyObject*>(self->parent), "_extensions_by_name"));
@@ -282,8 +212,6 @@ static PyMappingMethods MpMethods = {
#define EDMETHOD(name, args, doc) { #name, (PyCFunction)name, args, doc }
static PyMethodDef Methods[] = {
- EDMETHOD(ClearExtension, METH_O, "Clears an extension from the object."),
- EDMETHOD(HasExtension, METH_O, "Checks if the object has an extension."),
EDMETHOD(_FindExtensionByName, METH_O,
"Finds an extension by name."),
EDMETHOD(_FindExtensionByNumber, METH_O,
diff --git a/python/google/protobuf/pyext/extension_dict.h b/python/google/protobuf/pyext/extension_dict.h
index 2456eda1..65b87862 100644
--- a/python/google/protobuf/pyext/extension_dict.h
+++ b/python/google/protobuf/pyext/extension_dict.h
@@ -86,49 +86,6 @@ namespace extension_dict {
// Builds an Extensions dict for a specific message.
ExtensionDict* NewExtensionDict(CMessage *parent);
-// Gets the number of extension values in this ExtensionDict as a python object.
-//
-// Returns a new reference.
-PyObject* len(ExtensionDict* self);
-
-// Releases extensions referenced outside this dictionary to keep outside
-// references alive.
-//
-// Returns 0 on success, -1 on failure.
-int ReleaseExtension(ExtensionDict* self,
- PyObject* extension,
- const FieldDescriptor* descriptor);
-
-// Gets an extension from the dict for the given extension descriptor.
-//
-// Returns a new reference.
-PyObject* subscript(ExtensionDict* self, PyObject* key);
-
-// Assigns a value to an extension in the dict. Can only be used for singular
-// simple types.
-//
-// Returns 0 on success, -1 on failure.
-int ass_subscript(ExtensionDict* self, PyObject* key, PyObject* value);
-
-// Clears an extension from the dict. Will release the extension if there
-// is still an external reference left to it.
-//
-// Returns None on success.
-PyObject* ClearExtension(ExtensionDict* self,
- PyObject* extension);
-
-// Gets an extension from the dict given the extension name as opposed to
-// descriptor.
-//
-// Returns a new reference.
-PyObject* _FindExtensionByName(ExtensionDict* self, PyObject* name);
-
-// Gets an extension from the dict given the extension field number as
-// opposed to descriptor.
-//
-// Returns a new reference.
-PyObject* _FindExtensionByNumber(ExtensionDict* self, PyObject* number);
-
} // namespace extension_dict
} // namespace python
} // namespace protobuf
diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc
index 0987b898..318c2e7c 100644
--- a/python/google/protobuf/pyext/map_container.cc
+++ b/python/google/protobuf/pyext/map_container.cc
@@ -42,7 +42,9 @@
#include <google/protobuf/map_field.h>
#include <google/protobuf/map.h>
#include <google/protobuf/message.h>
+#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/repeated_composite_container.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#if PY_MAJOR_VERSION >= 3
@@ -328,6 +330,15 @@ PyObject* Clear(PyObject* _self) {
Py_RETURN_NONE;
}
+PyObject* GetEntryClass(PyObject* _self) {
+ MapContainer* self = GetMap(_self);
+ CMessageClass* message_class = message_factory::GetMessageClass(
+ cmessage::GetFactoryForMessage(self->parent),
+ self->parent_field_descriptor->message_type());
+ Py_XINCREF(message_class);
+ return reinterpret_cast<PyObject*>(message_class);
+}
+
PyObject* MapReflectionFriend::Contains(PyObject* _self, PyObject* key) {
MapContainer* self = GetMap(_self);
@@ -400,12 +411,7 @@ PyObject *NewScalarMapContainer(
return NULL;
}
-#if PY_MAJOR_VERSION >= 3
- ScopedPyObjectPtr obj(PyType_GenericAlloc(
- reinterpret_cast<PyTypeObject *>(ScalarMapContainer_Type), 0));
-#else
- ScopedPyObjectPtr obj(PyType_GenericAlloc(&ScalarMapContainer_Type, 0));
-#endif
+ ScopedPyObjectPtr obj(PyType_GenericAlloc(ScalarMapContainer_Type, 0));
if (obj.get() == NULL) {
return PyErr_Format(PyExc_RuntimeError,
"Could not allocate new container.");
@@ -527,6 +533,8 @@ static PyMethodDef ScalarMapMethods[] = {
"Removes all elements from the map." },
{ "get", ScalarMapGet, METH_VARARGS,
"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." },
/*
{ "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
"Makes a deep copy of the class." },
@@ -536,6 +544,7 @@ static PyMethodDef ScalarMapMethods[] = {
{NULL, NULL},
};
+PyTypeObject *ScalarMapContainer_Type;
#if PY_MAJOR_VERSION >= 3
static PyType_Slot ScalarMapContainer_Type_slots[] = {
{Py_tp_dealloc, (void *)ScalarMapDealloc},
@@ -554,7 +563,6 @@ static PyMethodDef ScalarMapMethods[] = {
Py_TPFLAGS_DEFAULT,
ScalarMapContainer_Type_slots
};
- PyObject *ScalarMapContainer_Type;
#else
static PyMappingMethods ScalarMapMappingMethods = {
MapReflectionFriend::Length, // mp_length
@@ -562,7 +570,7 @@ static PyMethodDef ScalarMapMethods[] = {
MapReflectionFriend::ScalarMapSetItem, // mp_ass_subscript
};
- PyTypeObject ScalarMapContainer_Type = {
+ PyTypeObject _ScalarMapContainer_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".ScalarMapContainer", // tp_name
sizeof(MapContainer), // tp_basicsize
@@ -643,12 +651,7 @@ PyObject* NewMessageMapContainer(
return NULL;
}
-#if PY_MAJOR_VERSION >= 3
- PyObject* obj = PyType_GenericAlloc(
- reinterpret_cast<PyTypeObject *>(MessageMapContainer_Type), 0);
-#else
- PyObject* obj = PyType_GenericAlloc(&MessageMapContainer_Type, 0);
-#endif
+ PyObject* obj = PyType_GenericAlloc(MessageMapContainer_Type, 0);
if (obj == NULL) {
return PyErr_Format(PyExc_RuntimeError,
"Could not allocate new container.");
@@ -780,6 +783,8 @@ static PyMethodDef MessageMapMethods[] = {
"Gets the value for the given key if present, or otherwise a default" },
{ "get_or_create", MapReflectionFriend::MessageMapGetItem, METH_O,
"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." },
/*
{ "__deepcopy__", (PyCFunction)DeepCopy, METH_VARARGS,
"Makes a deep copy of the class." },
@@ -789,6 +794,7 @@ static PyMethodDef MessageMapMethods[] = {
{NULL, NULL},
};
+PyTypeObject *MessageMapContainer_Type;
#if PY_MAJOR_VERSION >= 3
static PyType_Slot MessageMapContainer_Type_slots[] = {
{Py_tp_dealloc, (void *)MessageMapDealloc},
@@ -807,8 +813,6 @@ static PyMethodDef MessageMapMethods[] = {
Py_TPFLAGS_DEFAULT,
MessageMapContainer_Type_slots
};
-
- PyObject *MessageMapContainer_Type;
#else
static PyMappingMethods MessageMapMappingMethods = {
MapReflectionFriend::Length, // mp_length
@@ -816,7 +820,7 @@ static PyMethodDef MessageMapMethods[] = {
MapReflectionFriend::MessageMapSetItem, // mp_ass_subscript
};
- PyTypeObject MessageMapContainer_Type = {
+ PyTypeObject _MessageMapContainer_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
FULL_MODULE_NAME ".MessageMapContainer", // tp_name
sizeof(MessageMapContainer), // tp_basicsize
@@ -965,6 +969,63 @@ PyTypeObject MapIterator_Type = {
0, // tp_init
};
+bool InitMapContainers() {
+ // ScalarMapContainer_Type derives from our MutableMapping type.
+ ScopedPyObjectPtr containers(PyImport_ImportModule(
+ "google.protobuf.internal.containers"));
+ if (containers == NULL) {
+ return false;
+ }
+
+ ScopedPyObjectPtr mutable_mapping(
+ PyObject_GetAttrString(containers.get(), "MutableMapping"));
+ if (mutable_mapping == NULL) {
+ return false;
+ }
+
+ if (!PyObject_TypeCheck(mutable_mapping.get(), &PyType_Type)) {
+ return false;
+ }
+
+ Py_INCREF(mutable_mapping.get());
+#if PY_MAJOR_VERSION >= 3
+ PyObject* bases = PyTuple_New(1);
+ PyTuple_SET_ITEM(bases, 0, mutable_mapping.get());
+
+ ScalarMapContainer_Type = reinterpret_cast<PyTypeObject*>(
+ PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases));
+#else
+ _ScalarMapContainer_Type.tp_base =
+ reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
+
+ if (PyType_Ready(&_ScalarMapContainer_Type) < 0) {
+ return false;
+ }
+
+ ScalarMapContainer_Type = &_ScalarMapContainer_Type;
+#endif
+
+ if (PyType_Ready(&MapIterator_Type) < 0) {
+ return false;
+ }
+
+#if PY_MAJOR_VERSION >= 3
+ MessageMapContainer_Type = reinterpret_cast<PyTypeObject*>(
+ PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases));
+#else
+ Py_INCREF(mutable_mapping.get());
+ _MessageMapContainer_Type.tp_base =
+ reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
+
+ if (PyType_Ready(&_MessageMapContainer_Type) < 0) {
+ return false;
+ }
+
+ MessageMapContainer_Type = &_MessageMapContainer_Type;
+#endif
+ return true;
+}
+
} // namespace python
} // namespace protobuf
} // namespace google
diff --git a/python/google/protobuf/pyext/map_container.h b/python/google/protobuf/pyext/map_container.h
index fbd6713f..615657b0 100644
--- a/python/google/protobuf/pyext/map_container.h
+++ b/python/google/protobuf/pyext/map_container.h
@@ -112,16 +112,10 @@ struct MessageMapContainer : public MapContainer {
PyObject* message_dict;
};
-#if PY_MAJOR_VERSION >= 3
- extern PyObject *MessageMapContainer_Type;
- extern PyType_Spec MessageMapContainer_Type_spec;
- extern PyObject *ScalarMapContainer_Type;
- extern PyType_Spec ScalarMapContainer_Type_spec;
-#else
- extern PyTypeObject MessageMapContainer_Type;
- extern PyTypeObject ScalarMapContainer_Type;
-#endif
+bool InitMapContainers();
+extern PyTypeObject* MessageMapContainer_Type;
+extern PyTypeObject* ScalarMapContainer_Type;
extern PyTypeObject MapIterator_Type; // Both map types use the same iterator.
// Builds a MapContainer object, from a parent message and a
diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc
index 5535338d..6626ddef 100644
--- a/python/google/protobuf/pyext/message.cc
+++ b/python/google/protobuf/pyext/message.cc
@@ -63,6 +63,7 @@
#include <google/protobuf/pyext/repeated_composite_container.h>
#include <google/protobuf/pyext/repeated_scalar_container.h>
#include <google/protobuf/pyext/map_container.h>
+#include <google/protobuf/pyext/message_factory.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#include <google/protobuf/stubs/strutil.h>
@@ -244,6 +245,12 @@ static PyObject* New(PyTypeObject* type,
return NULL;
}
+ // Messages have no __dict__
+ ScopedPyObjectPtr slots(PyTuple_New(0));
+ if (PyDict_SetItemString(dict, "__slots__", slots.get()) < 0) {
+ return NULL;
+ }
+
// Build the arguments to the base metaclass.
// We change the __bases__ classes.
ScopedPyObjectPtr new_args;
@@ -300,16 +307,19 @@ static PyObject* New(PyTypeObject* type,
newtype->message_descriptor = descriptor;
// TODO(amauryfa): Don't always use the canonical pool of the descriptor,
// use the MessageFactory optionally passed in the class dict.
- newtype->py_descriptor_pool = GetDescriptorPool_FromPool(
- descriptor->file()->pool());
- if (newtype->py_descriptor_pool == NULL) {
+ PyDescriptorPool* py_descriptor_pool =
+ GetDescriptorPool_FromPool(descriptor->file()->pool());
+ if (py_descriptor_pool == NULL) {
return NULL;
}
- Py_INCREF(newtype->py_descriptor_pool);
+ newtype->py_message_factory = py_descriptor_pool->py_message_factory;
+ Py_INCREF(newtype->py_message_factory);
- // Add the message to the DescriptorPool.
- if (cdescriptor_pool::RegisterMessageClass(newtype->py_descriptor_pool,
- descriptor, newtype) < 0) {
+ // Register the message in the MessageFactory.
+ // TODO(amauryfa): Move this call to MessageFactory.GetPrototype() when the
+ // MessageFactory is fully implemented in C++.
+ if (message_factory::RegisterMessageClass(newtype->py_message_factory,
+ descriptor, newtype) < 0) {
return NULL;
}
@@ -321,8 +331,8 @@ static PyObject* New(PyTypeObject* type,
}
static void Dealloc(CMessageClass *self) {
- Py_DECREF(self->py_message_descriptor);
- Py_DECREF(self->py_descriptor_pool);
+ Py_XDECREF(self->py_message_descriptor);
+ Py_XDECREF(self->py_message_factory);
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
@@ -752,15 +762,9 @@ bool CheckFieldBelongsToMessage(const FieldDescriptor* field_descriptor,
namespace cmessage {
-PyDescriptorPool* GetDescriptorPoolForMessage(CMessage* message) {
- // No need to check the type: the type of instances of CMessage is always
- // an instance of CMessageClass. Let's prove it with a debug-only check.
+PyMessageFactory* GetFactoryForMessage(CMessage* message) {
GOOGLE_DCHECK(PyObject_TypeCheck(message, &CMessage_Type));
- return reinterpret_cast<CMessageClass*>(Py_TYPE(message))->py_descriptor_pool;
-}
-
-MessageFactory* GetFactoryForMessage(CMessage* message) {
- return GetDescriptorPoolForMessage(message)->message_factory;
+ return reinterpret_cast<CMessageClass*>(Py_TYPE(message))->py_message_factory;
}
static int MaybeReleaseOverlappingOneofField(
@@ -813,7 +817,8 @@ static Message* GetMutableMessage(
return NULL;
}
return reflection->MutableMessage(
- parent_message, parent_field, GetFactoryForMessage(parent));
+ parent_message, parent_field,
+ GetFactoryForMessage(parent)->message_factory);
}
struct FixupMessageReference : public ChildVisitor {
@@ -1172,6 +1177,8 @@ int InitAttributes(CMessage* self, PyObject* args, PyObject* kwargs) {
}
CMessage* cmessage = reinterpret_cast<CMessage*>(message.get());
if (PyDict_Check(value)) {
+ // Make the message exist even if the dict is empty.
+ AssureWritable(cmessage);
if (InitAttributes(cmessage, NULL, value) < 0) {
return -1;
}
@@ -1231,7 +1238,7 @@ static PyObject* New(PyTypeObject* cls,
if (message_descriptor == NULL) {
return NULL;
}
- const Message* default_message = type->py_descriptor_pool->message_factory
+ const Message* default_message = type->py_message_factory->message_factory
->GetPrototype(message_descriptor);
if (default_message == NULL) {
PyErr_SetString(PyExc_TypeError, message_descriptor->full_name().c_str());
@@ -1292,6 +1299,9 @@ struct ClearWeakReferences : public ChildVisitor {
};
static void Dealloc(CMessage* self) {
+ if (self->weakreflist) {
+ PyObject_ClearWeakRefs(reinterpret_cast<PyObject*>(self));
+ }
// Null out all weak references from children to this message.
GOOGLE_CHECK_EQ(0, ForEachCompositeField(self, ClearWeakReferences()));
if (self->extensions) {
@@ -1459,18 +1469,20 @@ PyObject* HasField(CMessage* self, PyObject* arg) {
}
PyObject* ClearExtension(CMessage* self, PyObject* extension) {
+ const FieldDescriptor* descriptor = GetExtensionDescriptor(extension);
+ if (descriptor == NULL) {
+ return NULL;
+ }
if (self->extensions != NULL) {
- return extension_dict::ClearExtension(self->extensions, extension);
- } else {
- const FieldDescriptor* descriptor = GetExtensionDescriptor(extension);
- if (descriptor == NULL) {
- return NULL;
- }
- if (ScopedPyObjectPtr(ClearFieldByDescriptor(self, descriptor)) == NULL) {
- return NULL;
+ PyObject* value = PyDict_GetItem(self->extensions->values, extension);
+ if (value != NULL) {
+ if (InternalReleaseFieldByDescriptor(self, descriptor, value) < 0) {
+ return NULL;
+ }
+ PyDict_DelItem(self->extensions->values, extension);
}
}
- Py_RETURN_NONE;
+ return ClearFieldByDescriptor(self, descriptor);
}
PyObject* HasExtension(CMessage* self, PyObject* extension) {
@@ -1556,7 +1568,7 @@ int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner) {
Message* ReleaseMessage(CMessage* self,
const Descriptor* descriptor,
const FieldDescriptor* field_descriptor) {
- MessageFactory* message_factory = GetFactoryForMessage(self);
+ MessageFactory* message_factory = GetFactoryForMessage(self)->message_factory;
Message* released_message = self->message->GetReflection()->ReleaseMessage(
self->message, field_descriptor, message_factory);
// ReleaseMessage will return NULL which differs from
@@ -1624,12 +1636,19 @@ int InternalReleaseFieldByDescriptor(
PyObject* ClearFieldByDescriptor(
CMessage* self,
- const FieldDescriptor* descriptor) {
- if (!CheckFieldBelongsToMessage(descriptor, self->message)) {
+ const FieldDescriptor* field_descriptor) {
+ if (!CheckFieldBelongsToMessage(field_descriptor, self->message)) {
return NULL;
}
AssureWritable(self);
- self->message->GetReflection()->ClearField(self->message, descriptor);
+ Message* message = self->message;
+ message->GetReflection()->ClearField(message, field_descriptor);
+ if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
+ !message->GetReflection()->SupportsUnknownEnumValues()) {
+ UnknownFieldSet* unknown_field_set =
+ message->GetReflection()->MutableUnknownFields(message);
+ unknown_field_set->DeleteByNumber(field_descriptor->number());
+ }
Py_RETURN_NONE;
}
@@ -1665,27 +1684,17 @@ PyObject* ClearField(CMessage* self, PyObject* arg) {
arg = arg_in_oneof.get();
}
- PyObject* composite_field = self->composite_fields ?
- PyDict_GetItem(self->composite_fields, arg) : NULL;
-
- // Only release the field if there's a possibility that there are
- // references to it.
- if (composite_field != NULL) {
- if (InternalReleaseFieldByDescriptor(self, field_descriptor,
- composite_field) < 0) {
- return NULL;
+ // Release the field if it exists in the dict of composite fields.
+ if (self->composite_fields) {
+ PyObject* value = PyDict_GetItem(self->composite_fields, arg);
+ if (value != NULL) {
+ if (InternalReleaseFieldByDescriptor(self, field_descriptor, value) < 0) {
+ return NULL;
+ }
+ PyDict_DelItem(self->composite_fields, arg);
}
- PyDict_DelItem(self->composite_fields, arg);
- }
- message->GetReflection()->ClearField(message, field_descriptor);
- if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
- !message->GetReflection()->SupportsUnknownEnumValues()) {
- UnknownFieldSet* unknown_field_set =
- message->GetReflection()->MutableUnknownFields(message);
- unknown_field_set->DeleteByNumber(field_descriptor->number());
}
-
- Py_RETURN_NONE;
+ return ClearFieldByDescriptor(self, field_descriptor);
}
PyObject* Clear(CMessage* self) {
@@ -1896,7 +1905,11 @@ static PyObject* CopyFrom(CMessage* self, PyObject* arg) {
// get OOM errors. The protobuf APIs do not provide any tools for processing
// protobufs in chunks. If you have protos this big you should break them up if
// it is at all convenient to do so.
+#ifdef PROTOBUF_PYTHON_ALLOW_OVERSIZE_PROTOS
+static bool allow_oversize_protos = true;
+#else
static bool allow_oversize_protos = false;
+#endif
// Provide a method in the module to set allow_oversize_protos to a boolean
// value. This method returns the newly value of allow_oversize_protos.
@@ -1927,8 +1940,8 @@ static PyObject* MergeFromString(CMessage* self, PyObject* arg) {
if (allow_oversize_protos) {
input.SetTotalBytesLimit(INT_MAX, INT_MAX);
}
- PyDescriptorPool* pool = GetDescriptorPoolForMessage(self);
- input.SetExtensionRegistry(pool->pool, pool->message_factory);
+ PyMessageFactory* factory = GetFactoryForMessage(self);
+ input.SetExtensionRegistry(factory->pool->pool, factory->message_factory);
bool success = self->message->MergePartialFromCodedStream(&input);
if (success) {
return PyInt_FromLong(input.CurrentPosition());
@@ -2108,8 +2121,8 @@ static PyObject* ListFields(CMessage* self) {
// is no message class and we cannot retrieve the value.
// TODO(amauryfa): consider building the class on the fly!
if (fields[i]->message_type() != NULL &&
- cdescriptor_pool::GetMessageClass(
- GetDescriptorPoolForMessage(self),
+ message_factory::GetMessageClass(
+ GetFactoryForMessage(self),
fields[i]->message_type()) == NULL) {
PyErr_Clear();
continue;
@@ -2306,12 +2319,12 @@ PyObject* InternalGetScalar(const Message* message,
PyObject* InternalGetSubMessage(
CMessage* self, const FieldDescriptor* field_descriptor) {
const Reflection* reflection = self->message->GetReflection();
- PyDescriptorPool* pool = GetDescriptorPoolForMessage(self);
+ PyMessageFactory* factory = GetFactoryForMessage(self);
const Message& sub_message = reflection->GetMessage(
- *self->message, field_descriptor, pool->message_factory);
+ *self->message, field_descriptor, factory->message_factory);
- CMessageClass* message_class = cdescriptor_pool::GetMessageClass(
- pool, field_descriptor->message_type());
+ CMessageClass* message_class = message_factory::GetMessageClass(
+ factory, field_descriptor->message_type());
if (message_class == NULL) {
return NULL;
}
@@ -2656,8 +2669,8 @@ PyObject* GetAttr(CMessage* self, PyObject* name) {
const Descriptor* entry_type = field_descriptor->message_type();
const FieldDescriptor* value_type = entry_type->FindFieldByName("value");
if (value_type->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- CMessageClass* value_class = cdescriptor_pool::GetMessageClass(
- GetDescriptorPoolForMessage(self), value_type->message_type());
+ CMessageClass* value_class = message_factory::GetMessageClass(
+ GetFactoryForMessage(self), value_type->message_type());
if (value_class == NULL) {
return NULL;
}
@@ -2679,8 +2692,8 @@ PyObject* GetAttr(CMessage* self, PyObject* name) {
if (field_descriptor->label() == FieldDescriptor::LABEL_REPEATED) {
PyObject* py_container = NULL;
if (field_descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- CMessageClass* message_class = cdescriptor_pool::GetMessageClass(
- GetDescriptorPoolForMessage(self), field_descriptor->message_type());
+ CMessageClass* message_class = message_factory::GetMessageClass(
+ GetFactoryForMessage(self), field_descriptor->message_type());
if (message_class == NULL) {
return NULL;
}
@@ -2775,7 +2788,7 @@ PyTypeObject CMessage_Type = {
0, // tp_traverse
0, // tp_clear
(richcmpfunc)cmessage::RichCompare, // tp_richcompare
- 0, // tp_weaklistoffset
+ offsetof(CMessage, weakreflist), // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
cmessage::Methods, // tp_methods
@@ -2822,13 +2835,6 @@ static Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) {
return cmsg->message;
}
-static const char module_docstring[] =
-"python-proto2 is a module that can be used to enhance proto2 Python API\n"
-"performance.\n"
-"\n"
-"It provides access to the protocol buffers C++ reflection API that\n"
-"implements the basic protocol buffer functions.";
-
void InitGlobals() {
// TODO(gps): Check all return values in this function for NULL and propagate
// the error (MemoryError) on up to result in an import failure. These should
@@ -2863,6 +2869,11 @@ bool InitProto2MessageModule(PyObject *m) {
return false;
}
+ // Initialize types and globals in message_factory.cc
+ if (!InitMessageFactory()) {
+ return false;
+ }
+
// Initialize constants defined in this file.
InitGlobals();
@@ -2944,69 +2955,15 @@ bool InitProto2MessageModule(PyObject *m) {
}
// Initialize Map container types.
- {
- // ScalarMapContainer_Type derives from our MutableMapping type.
- ScopedPyObjectPtr containers(PyImport_ImportModule(
- "google.protobuf.internal.containers"));
- if (containers == NULL) {
- return false;
- }
-
- ScopedPyObjectPtr mutable_mapping(
- PyObject_GetAttrString(containers.get(), "MutableMapping"));
- if (mutable_mapping == NULL) {
- return false;
- }
-
- if (!PyObject_TypeCheck(mutable_mapping.get(), &PyType_Type)) {
- return false;
- }
-
- Py_INCREF(mutable_mapping.get());
-#if PY_MAJOR_VERSION >= 3
- PyObject* bases = PyTuple_New(1);
- PyTuple_SET_ITEM(bases, 0, mutable_mapping.get());
-
- ScalarMapContainer_Type =
- PyType_FromSpecWithBases(&ScalarMapContainer_Type_spec, bases);
- PyModule_AddObject(m, "ScalarMapContainer", ScalarMapContainer_Type);
-#else
- ScalarMapContainer_Type.tp_base =
- reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
-
- if (PyType_Ready(&ScalarMapContainer_Type) < 0) {
- return false;
- }
-
- PyModule_AddObject(m, "ScalarMapContainer",
- reinterpret_cast<PyObject*>(&ScalarMapContainer_Type));
-#endif
-
- if (PyType_Ready(&MapIterator_Type) < 0) {
- return false;
- }
-
- PyModule_AddObject(m, "MapIterator",
- reinterpret_cast<PyObject*>(&MapIterator_Type));
-
-
-#if PY_MAJOR_VERSION >= 3
- MessageMapContainer_Type =
- PyType_FromSpecWithBases(&MessageMapContainer_Type_spec, bases);
- PyModule_AddObject(m, "MessageMapContainer", MessageMapContainer_Type);
-#else
- Py_INCREF(mutable_mapping.get());
- MessageMapContainer_Type.tp_base =
- reinterpret_cast<PyTypeObject*>(mutable_mapping.get());
-
- if (PyType_Ready(&MessageMapContainer_Type) < 0) {
- return false;
- }
-
- PyModule_AddObject(m, "MessageMapContainer",
- reinterpret_cast<PyObject*>(&MessageMapContainer_Type));
-#endif
+ if (!InitMapContainers()) {
+ return false;
}
+ PyModule_AddObject(m, "ScalarMapContainer",
+ reinterpret_cast<PyObject*>(ScalarMapContainer_Type));
+ PyModule_AddObject(m, "MessageMapContainer",
+ reinterpret_cast<PyObject*>(MessageMapContainer_Type));
+ PyModule_AddObject(m, "MapIterator",
+ reinterpret_cast<PyObject*>(&MapIterator_Type));
if (PyType_Ready(&ExtensionDict_Type) < 0) {
return false;
diff --git a/python/google/protobuf/pyext/message.h b/python/google/protobuf/pyext/message.h
index c44a2ae2..1550724c 100644
--- a/python/google/protobuf/pyext/message.h
+++ b/python/google/protobuf/pyext/message.h
@@ -62,7 +62,7 @@ using internal::shared_ptr;
namespace python {
struct ExtensionDict;
-struct PyDescriptorPool;
+struct PyMessageFactory;
typedef struct CMessage {
PyObject_HEAD;
@@ -112,6 +112,9 @@ typedef struct CMessage {
// Similar to composite_fields, acting as a cache, but also contains the
// required extension dict logic.
ExtensionDict* extensions;
+
+ // Implements the "weakref" protocol for this object.
+ PyObject* weakreflist;
} CMessage;
extern PyTypeObject CMessage_Type;
@@ -132,14 +135,11 @@ struct CMessageClass {
// Owned reference, used to keep the pointer above alive.
PyObject* py_message_descriptor;
- // The Python DescriptorPool used to create the class. It is needed to resolve
+ // The Python MessageFactory used to create the class. It is needed to resolve
// fields descriptors, including extensions fields; its C++ MessageFactory is
// used to instantiate submessages.
- // This can be different from DESCRIPTOR.file.pool, in the case of a custom
- // DescriptorPool which defines new extensions.
- // We own the reference, because it's important to keep the descriptors and
- // factory alive.
- PyDescriptorPool* py_descriptor_pool;
+ // We own the reference, because it's important to keep the factory alive.
+ PyMessageFactory* py_message_factory;
PyObject* AsPyObject() {
return reinterpret_cast<PyObject*>(this);
@@ -154,14 +154,6 @@ namespace cmessage {
// The caller must fill self->message, self->owner and eventually self->parent.
CMessage* NewEmptyMessage(CMessageClass* type);
-// Release a submessage from its proto tree, making it a new top-level messgae.
-// A new message will be created if this is a read-only default instance.
-//
-// Corresponds to reflection api method ReleaseMessage.
-int ReleaseSubMessage(CMessage* self,
- const FieldDescriptor* field_descriptor,
- CMessage* child_cmessage);
-
// Retrieves the C++ descriptor of a Python Extension descriptor.
// On error, return NULL with an exception set.
const FieldDescriptor* GetExtensionDescriptor(PyObject* extension);
@@ -262,14 +254,13 @@ int SetOwner(CMessage* self, const shared_ptr<Message>& new_owner);
int AssureWritable(CMessage* self);
-// Returns the "best" DescriptorPool for the given message.
-// This is often equivalent to message.DESCRIPTOR.pool, but not always, when
-// the message class was created from a MessageFactory using a custom pool which
-// uses the generated pool as an underlay.
+// Returns the message factory for the given message.
+// This is equivalent to message.MESSAGE_FACTORY
//
-// The returned pool is suitable for finding fields and building submessages,
+// The returned factory is suitable for finding fields and building submessages,
// even in the case of extensions.
-PyDescriptorPool* GetDescriptorPoolForMessage(CMessage* message);
+// Returns a *borrowed* reference, and never fails because we pass a CMessage.
+PyMessageFactory* GetFactoryForMessage(CMessage* message);
PyObject* SetAllowOversizeProtos(PyObject* m, PyObject* arg);
diff --git a/python/google/protobuf/pyext/message_factory.cc b/python/google/protobuf/pyext/message_factory.cc
new file mode 100644
index 00000000..2ad89022
--- /dev/null
+++ b/python/google/protobuf/pyext/message_factory.cc
@@ -0,0 +1,214 @@
+// 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 <Python.h>
+
+#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/pyext/descriptor.h>
+#include <google/protobuf/pyext/message.h>
+#include <google/protobuf/pyext/message_factory.h>
+#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
+
+#if PY_MAJOR_VERSION >= 3
+ #if PY_VERSION_HEX < 0x03030000
+ #error "Python 3.0 - 3.2 are not supported."
+ #endif
+ #define PyString_AsStringAndSize(ob, charpp, sizep) \
+ (PyUnicode_Check(ob)? \
+ ((*(charpp) = PyUnicode_AsUTF8AndSize(ob, (sizep))) == NULL? -1: 0): \
+ PyBytes_AsStringAndSize(ob, (charpp), (sizep)))
+#endif
+
+namespace google {
+namespace protobuf {
+namespace python {
+
+namespace message_factory {
+
+PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool) {
+ PyMessageFactory* factory = reinterpret_cast<PyMessageFactory*>(
+ PyType_GenericAlloc(type, 0));
+ if (factory == NULL) {
+ return NULL;
+ }
+
+ DynamicMessageFactory* message_factory = new DynamicMessageFactory();
+ // This option might be the default some day.
+ message_factory->SetDelegateToGeneratedFactory(true);
+ factory->message_factory = message_factory;
+
+ factory->pool = pool;
+ // TODO(amauryfa): When the MessageFactory is not created from the
+ // DescriptorPool this reference should be owned, not borrowed.
+ // Py_INCREF(pool);
+
+ factory->classes_by_descriptor = new PyMessageFactory::ClassesByMessageMap();
+
+ return factory;
+}
+
+PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) {
+ static char* kwlist[] = {"pool", 0};
+ PyObject* pool = NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist, &pool)) {
+ return NULL;
+ }
+ ScopedPyObjectPtr owned_pool;
+ if (pool == NULL || pool == Py_None) {
+ owned_pool.reset(PyObject_CallFunction(
+ reinterpret_cast<PyObject*>(&PyDescriptorPool_Type), NULL));
+ if (owned_pool == NULL) {
+ return NULL;
+ }
+ pool = owned_pool.get();
+ } else {
+ if (!PyObject_TypeCheck(pool, &PyDescriptorPool_Type)) {
+ PyErr_Format(PyExc_TypeError, "Expected a DescriptorPool, got %s",
+ pool->ob_type->tp_name);
+ return NULL;
+ }
+ }
+
+ return reinterpret_cast<PyObject*>(
+ NewMessageFactory(type, reinterpret_cast<PyDescriptorPool*>(pool)));
+}
+
+static void Dealloc(PyMessageFactory* self) {
+ // TODO(amauryfa): When the MessageFactory is not created from the
+ // DescriptorPool this reference should be owned, not borrowed.
+ // Py_CLEAR(self->pool);
+ typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
+ for (iterator it = self->classes_by_descriptor->begin();
+ it != self->classes_by_descriptor->end(); ++it) {
+ Py_DECREF(it->second);
+ }
+ delete self->classes_by_descriptor;
+ delete self->message_factory;
+ Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
+}
+
+// Add a message class to our database.
+int RegisterMessageClass(PyMessageFactory* self,
+ const Descriptor* message_descriptor,
+ CMessageClass* message_class) {
+ Py_INCREF(message_class);
+ typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
+ std::pair<iterator, bool> ret = self->classes_by_descriptor->insert(
+ std::make_pair(message_descriptor, message_class));
+ if (!ret.second) {
+ // Update case: DECREF the previous value.
+ Py_DECREF(ret.first->second);
+ ret.first->second = message_class;
+ }
+ return 0;
+}
+
+// Retrieve the message class added to our database.
+CMessageClass* GetMessageClass(PyMessageFactory* self,
+ const Descriptor* message_descriptor) {
+ typedef PyMessageFactory::ClassesByMessageMap::iterator iterator;
+ iterator ret = self->classes_by_descriptor->find(message_descriptor);
+ if (ret == self->classes_by_descriptor->end()) {
+ PyErr_Format(PyExc_TypeError, "No message class registered for '%s'",
+ message_descriptor->full_name().c_str());
+ return NULL;
+ } else {
+ return ret->second;
+ }
+}
+
+static PyMethodDef Methods[] = {
+ {NULL}};
+
+static PyObject* GetPool(PyMessageFactory* self, void* closure) {
+ Py_INCREF(self->pool);
+ return reinterpret_cast<PyObject*>(self->pool);
+}
+
+static PyGetSetDef Getters[] = {
+ {"pool", (getter)GetPool, NULL, "DescriptorPool"},
+ {NULL}
+};
+
+} // namespace message_factory
+
+PyTypeObject PyMessageFactory_Type = {
+ PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME
+ ".MessageFactory", // tp_name
+ sizeof(PyMessageFactory), // tp_basicsize
+ 0, // tp_itemsize
+ (destructor)message_factory::Dealloc, // tp_dealloc
+ 0, // tp_print
+ 0, // tp_getattr
+ 0, // tp_setattr
+ 0, // tp_compare
+ 0, // tp_repr
+ 0, // tp_as_number
+ 0, // tp_as_sequence
+ 0, // tp_as_mapping
+ 0, // tp_hash
+ 0, // tp_call
+ 0, // tp_str
+ 0, // tp_getattro
+ 0, // tp_setattro
+ 0, // tp_as_buffer
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
+ "A static Message Factory", // tp_doc
+ 0, // tp_traverse
+ 0, // tp_clear
+ 0, // tp_richcompare
+ 0, // tp_weaklistoffset
+ 0, // tp_iter
+ 0, // tp_iternext
+ message_factory::Methods, // tp_methods
+ 0, // tp_members
+ message_factory::Getters, // tp_getset
+ 0, // tp_base
+ 0, // tp_dict
+ 0, // tp_descr_get
+ 0, // tp_descr_set
+ 0, // tp_dictoffset
+ 0, // tp_init
+ 0, // tp_alloc
+ message_factory::New, // tp_new
+ PyObject_Del, // tp_free
+};
+
+bool InitMessageFactory() {
+ if (PyType_Ready(&PyMessageFactory_Type) < 0) {
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace python
+} // namespace protobuf
+} // namespace google
diff --git a/python/google/protobuf/pyext/message_factory.h b/python/google/protobuf/pyext/message_factory.h
new file mode 100644
index 00000000..07cccbfb
--- /dev/null
+++ b/python/google/protobuf/pyext/message_factory.h
@@ -0,0 +1,103 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__
+#define GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__
+
+#include <Python.h>
+
+#include <google/protobuf/stubs/hash.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/pyext/descriptor_pool.h>
+
+namespace google {
+namespace protobuf {
+class MessageFactory;
+
+namespace python {
+
+// The (meta) type of all Messages classes.
+struct CMessageClass;
+
+struct PyMessageFactory {
+ PyObject_HEAD
+
+ // DynamicMessageFactory used to create C++ instances of messages.
+ // This object cache the descriptors that were used, so the DescriptorPool
+ // needs to get rid of it before it can delete itself.
+ //
+ // Note: A C++ MessageFactory is different from the PyMessageFactory.
+ // The C++ one creates messages, when the Python one creates classes.
+ MessageFactory* message_factory;
+
+ // borrowed reference to a Python DescriptorPool.
+ // TODO(amauryfa): invert the dependency: the MessageFactory owns the
+ // DescriptorPool, not the opposite.
+ PyDescriptorPool* pool;
+
+ // Make our own mapping to retrieve Python classes from C++ descriptors.
+ //
+ // Descriptor pointers stored here are owned by the DescriptorPool above.
+ // Python references to classes are owned by this PyDescriptorPool.
+ typedef hash_map<const Descriptor*, CMessageClass*> ClassesByMessageMap;
+ ClassesByMessageMap* classes_by_descriptor;
+};
+
+extern PyTypeObject PyMessageFactory_Type;
+
+namespace message_factory {
+
+// Creates a new MessageFactory instance.
+PyMessageFactory* NewMessageFactory(PyTypeObject* type, PyDescriptorPool* pool);
+
+// Registers a new Python class for the given message descriptor.
+// On error, returns -1 with a Python exception set.
+int RegisterMessageClass(PyMessageFactory* self,
+ const Descriptor* message_descriptor,
+ CMessageClass* message_class);
+
+// Retrieves the Python class registered with the given message descriptor.
+//
+// Returns a *borrowed* reference if found, otherwise returns NULL with an
+// exception set.
+CMessageClass* GetMessageClass(PyMessageFactory* self,
+ const Descriptor* message_descriptor);
+
+} // namespace message_factory
+
+// Initialize objects used by this module.
+// On error, returns false with a Python exception set.
+bool InitMessageFactory();
+
+} // namespace python
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_PYTHON_CPP_MESSAGE_FACTORY_H__
diff --git a/python/google/protobuf/pyext/repeated_composite_container.cc b/python/google/protobuf/pyext/repeated_composite_container.cc
index bb2f6db2..43a2bc12 100644
--- a/python/google/protobuf/pyext/repeated_composite_container.cc
+++ b/python/google/protobuf/pyext/repeated_composite_container.cc
@@ -364,7 +364,7 @@ static int SortPythonMessages(RepeatedCompositeContainer* self,
ScopedPyObjectPtr m(PyObject_GetAttrString(self->child_messages, "sort"));
if (m == NULL)
return -1;
- if (PyObject_Call(m.get(), args, kwds) == NULL)
+ if (ScopedPyObjectPtr(PyObject_Call(m.get(), args, kwds)) == NULL)
return -1;
if (self->message != NULL) {
ReorderAttached(self);
diff --git a/python/google/protobuf/symbol_database.py b/python/google/protobuf/symbol_database.py
index aa466abd..ecbef211 100644
--- a/python/google/protobuf/symbol_database.py
+++ b/python/google/protobuf/symbol_database.py
@@ -129,7 +129,8 @@ class SymbolDatabase(message_factory.MessageFactory):
Only messages already created and registered will be returned; (this is the
case for imported _pb2 modules)
- But unlike MessageFactory, this version also returns nested messages.
+ But unlike MessageFactory, this version also returns already defined nested
+ messages, but does not register any message extensions.
Args:
files: The file names to extract messages from.
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py
index 06b79d77..90f6ce42 100755
--- a/python/google/protobuf/text_format.py
+++ b/python/google/protobuf/text_format.py
@@ -228,13 +228,13 @@ def _BuildMessageFromTypeName(type_name, descriptor_pool):
wasn't found matching type_name.
"""
# pylint: disable=g-import-not-at-top
- from google.protobuf import message_factory
- factory = message_factory.MessageFactory(descriptor_pool)
+ from google.protobuf import symbol_database
+ database = symbol_database.Default()
try:
message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
except KeyError:
return None
- message_type = factory.GetPrototype(message_descriptor)
+ message_type = database.GetPrototype(message_descriptor)
return message_type()
@@ -317,8 +317,7 @@ class _Printer(object):
# of this file to work around.
#
# TODO(haberman): refactor and optimize if this becomes an issue.
- entry_submsg = field.message_type._concrete_class(key=key,
- value=value[key])
+ entry_submsg = value.GetEntryClass()(key=key, value=value[key])
self.PrintField(field, entry_submsg)
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
for element in value:
@@ -749,8 +748,7 @@ class _Parser(object):
if field.is_extension:
sub_message = message.Extensions[field].add()
elif is_map_entry:
- # pylint: disable=protected-access
- sub_message = field.message_type._concrete_class()
+ sub_message = getattr(message, field.name).GetEntryClass()()
else:
sub_message = getattr(message, field.name).add()
else:
@@ -1448,9 +1446,9 @@ def ParseBool(text):
Raises:
ValueError: If text is not a valid boolean.
"""
- if text in ('true', 't', '1'):
+ if text in ('true', 't', '1', 'True'):
return True
- elif text in ('false', 'f', '0'):
+ elif text in ('false', 'f', '0', 'False'):
return False
else:
raise ValueError('Expected "true" or "false".')
diff --git a/python/tox.ini b/python/tox.ini
index cf8d5401..1600db21 100644
--- a/python/tox.ini
+++ b/python/tox.ini
@@ -12,7 +12,7 @@ setenv =
commands =
python setup.py -q build_py
python: python setup.py -q build
- cpp: python setup.py -q build --cpp_implementation --warnings_as_errors
+ cpp: python setup.py -q build --cpp_implementation --warnings_as_errors --compile_static_extension
python: python setup.py -q test -q
cpp: python setup.py -q test -q --cpp_implementation
python: python setup.py -q test_conformance
diff --git a/ruby/Gemfile.lock b/ruby/Gemfile.lock
deleted file mode 100644
index d0eb9cc4..00000000
--- a/ruby/Gemfile.lock
+++ /dev/null
@@ -1,30 +0,0 @@
-PATH
- remote: .
- specs:
- google-protobuf (3.0.0.alpha.5.0.5)
-
-GEM
- remote: https://rubygems.org/
- specs:
- power_assert (0.2.2)
- rake (10.4.2)
- rake-compiler (0.9.5)
- rake
- rake-compiler-dock (0.5.1)
- rubygems-tasks (0.2.4)
- test-unit (3.0.9)
- power_assert
-
-PLATFORMS
- java
- ruby
-
-DEPENDENCIES
- google-protobuf!
- rake-compiler
- rake-compiler-dock
- rubygems-tasks
- test-unit
-
-BUNDLED WITH
- 1.11.2
diff --git a/ruby/ext/google/protobuf_c/encode_decode.c b/ruby/ext/google/protobuf_c/encode_decode.c
index dd21a046..08c72bcc 100644
--- a/ruby/ext/google/protobuf_c/encode_decode.c
+++ b/ruby/ext/google/protobuf_c/encode_decode.c
@@ -255,10 +255,54 @@ typedef struct {
// value into the map.
typedef struct {
VALUE map;
+ const map_handlerdata_t* handlerdata;
char key_storage[NATIVE_SLOT_MAX_SIZE];
char value_storage[NATIVE_SLOT_MAX_SIZE];
} map_parse_frame_t;
+static void MapParseFrame_mark(void* _self) {
+ map_parse_frame_t* frame = _self;
+
+ // This shouldn't strictly be necessary since this should be rooted by the
+ // message itself, but it can't hurt.
+ rb_gc_mark(frame->map);
+
+ native_slot_mark(frame->handlerdata->key_field_type, &frame->key_storage);
+ native_slot_mark(frame->handlerdata->value_field_type, &frame->value_storage);
+}
+
+void MapParseFrame_free(void* self) {
+ xfree(self);
+}
+
+rb_data_type_t MapParseFrame_type = {
+ "MapParseFrame",
+ { MapParseFrame_mark, MapParseFrame_free, NULL },
+};
+
+// Array of Ruby objects wrapping map_parse_frame_t.
+// We don't allow multiple concurrent decodes, so we assume that this global
+// variable is specific to the "current" decode.
+VALUE map_parse_frames;
+
+static map_parse_frame_t* map_push_frame(VALUE map,
+ const map_handlerdata_t* handlerdata) {
+ map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
+ frame->handlerdata = handlerdata;
+ frame->map = map;
+ native_slot_init(handlerdata->key_field_type, &frame->key_storage);
+ native_slot_init(handlerdata->value_field_type, &frame->value_storage);
+
+ rb_ary_push(map_parse_frames,
+ TypedData_Wrap_Struct(rb_cObject, &MapParseFrame_type, frame));
+
+ return frame;
+}
+
+static void map_pop_frame() {
+ rb_ary_pop(map_parse_frames);
+}
+
// Handler to begin a map entry: allocates a temporary frame. This is the
// 'startsubmsg' handler on the msgdef that contains the map field.
static void *startmapentry_handler(void *closure, const void *hd) {
@@ -266,13 +310,7 @@ static void *startmapentry_handler(void *closure, const void *hd) {
const map_handlerdata_t* mapdata = hd;
VALUE map_rb = DEREF(msg, mapdata->ofs, VALUE);
- map_parse_frame_t* frame = ALLOC(map_parse_frame_t);
- frame->map = map_rb;
-
- native_slot_init(mapdata->key_field_type, &frame->key_storage);
- native_slot_init(mapdata->value_field_type, &frame->value_storage);
-
- return frame;
+ return map_push_frame(map_rb, mapdata);
}
// Handler to end a map entry: inserts the value defined during the message into
@@ -298,7 +336,7 @@ static bool endmap_handler(void *closure, const void *hd, upb_status* s) {
&frame->value_storage);
Map_index_set(frame->map, key, value);
- xfree(frame);
+ map_pop_frame();
return true;
}
@@ -737,6 +775,10 @@ VALUE Message_decode(VALUE klass, VALUE data) {
msg_rb = rb_class_new_instance(0, NULL, msgklass);
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
+ // We generally expect this to be clear already, but clear it in case parsing
+ // previously got interrupted somehow.
+ rb_ary_clear(map_parse_frames);
+
{
const upb_pbdecodermethod* method = msgdef_decodermethod(desc);
const upb_handlers* h = upb_pbdecodermethod_desthandlers(method);
@@ -781,6 +823,10 @@ VALUE Message_decode_json(VALUE klass, VALUE data) {
msg_rb = rb_class_new_instance(0, NULL, msgklass);
TypedData_Get_Struct(msg_rb, MessageHeader, &Message_type, msg);
+ // We generally expect this to be clear already, but clear it in case parsing
+ // previously got interrupted somehow.
+ rb_ary_clear(map_parse_frames);
+
{
const upb_json_parsermethod* method = msgdef_jsonparsermethod(desc);
stackenv se;
diff --git a/ruby/ext/google/protobuf_c/protobuf.c b/ruby/ext/google/protobuf_c/protobuf.c
index 7cde4aec..98963667 100644
--- a/ruby/ext/google/protobuf_c/protobuf.c
+++ b/ruby/ext/google/protobuf_c/protobuf.c
@@ -112,4 +112,6 @@ void Init_protobuf_c() {
upb_def_to_ruby_obj_map = rb_hash_new();
rb_gc_register_address(&upb_def_to_ruby_obj_map);
+ map_parse_frames = rb_ary_new();
+ rb_gc_register_address(&map_parse_frames);
}
diff --git a/ruby/ext/google/protobuf_c/protobuf.h b/ruby/ext/google/protobuf_c/protobuf.h
index 08b8d516..d5ced567 100644
--- a/ruby/ext/google/protobuf_c/protobuf.h
+++ b/ruby/ext/google/protobuf_c/protobuf.h
@@ -166,6 +166,8 @@ extern VALUE cBuilder;
extern VALUE cError;
extern VALUE cParseError;
+extern VALUE map_parse_frames;
+
// We forward-declare all of the Ruby method implementations here because we
// sometimes call the methods directly across .c files, rather than going
// through Ruby's method dispatching (e.g. during message parse). It's cleaner
diff --git a/ruby/ext/google/protobuf_c/repeated_field.c b/ruby/ext/google/protobuf_c/repeated_field.c
index 47c207a5..1c651c19 100644
--- a/ruby/ext/google/protobuf_c/repeated_field.c
+++ b/ruby/ext/google/protobuf_c/repeated_field.c
@@ -447,9 +447,8 @@ VALUE RepeatedField_eq(VALUE _self, VALUE _other) {
*/
VALUE RepeatedField_hash(VALUE _self) {
RepeatedField* self = ruby_to_RepeatedField(_self);
-
- VALUE hash = LL2NUM(0);
-
+ st_index_t h = rb_hash_start(0);
+ VALUE hash_sym = rb_intern("hash");
upb_fieldtype_t field_type = self->field_type;
VALUE field_type_class = self->field_type_class;
size_t elem_size = native_slot_size(field_type);
@@ -457,12 +456,11 @@ VALUE RepeatedField_hash(VALUE _self) {
for (int i = 0; i < self->size; i++, off += elem_size) {
void* mem = ((uint8_t *)self->elements) + off;
VALUE elem = native_slot_get(field_type, field_type_class, mem);
- hash = rb_funcall(hash, rb_intern("<<"), 1, INT2NUM(2));
- hash = rb_funcall(hash, rb_intern("^"), 1,
- rb_funcall(elem, rb_intern("hash"), 0));
+ h = rb_hash_uint(h, NUM2LONG(rb_funcall(elem, hash_sym, 0)));
}
+ h = rb_hash_end(h);
- return hash;
+ return INT2FIX(h);
}
/*
diff --git a/ruby/ext/google/protobuf_c/upb.c b/ruby/ext/google/protobuf_c/upb.c
index 976a3934..544ebc04 100644
--- a/ruby/ext/google/protobuf_c/upb.c
+++ b/ruby/ext/google/protobuf_c/upb.c
@@ -11175,7 +11175,7 @@ static bool parse_mapentry_key(upb_json_parser *p) {
sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
upb_sink_putstring(&subsink, sel, buf, len, NULL);
sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
- upb_sink_endstr(&subsink, sel);
+ upb_sink_endstr(&p->top->sink, sel);
multipart_end(p);
break;
}
diff --git a/ruby/google-protobuf.gemspec b/ruby/google-protobuf.gemspec
index 286d8fe3..19be14e5 100644
--- a/ruby/google-protobuf.gemspec
+++ b/ruby/google-protobuf.gemspec
@@ -1,6 +1,6 @@
Gem::Specification.new do |s|
s.name = "google-protobuf"
- s.version = "3.0.0"
+ s.version = "3.1.0"
s.licenses = ["BSD"]
s.summary = "Protocol Buffers"
s.description = "Protocol Buffers are Google's data interchange format."
@@ -10,16 +10,17 @@ Gem::Specification.new do |s|
s.require_paths = ["lib"]
s.files = Dir.glob('lib/**/*.rb')
if RUBY_PLATFORM == "java"
+ s.platform = "java"
s.files += ["lib/google/protobuf_java.jar"]
else
s.files += Dir.glob('ext/**/*')
s.extensions= ["ext/google/protobuf_c/extconf.rb"]
- s.add_development_dependency "rake-compiler-dock"
+ s.add_development_dependency "rake-compiler-dock", "~> 0.5.1"
end
s.test_files = ["tests/basic.rb",
"tests/stress.rb",
"tests/generated_code_test.rb"]
- s.add_development_dependency "rake-compiler"
- s.add_development_dependency "test-unit"
- s.add_development_dependency "rubygems-tasks"
+ s.add_development_dependency "rake-compiler", "~> 0.9.5"
+ s.add_development_dependency "test-unit", "~> 3.0.9"
+ s.add_development_dependency "rubygems-tasks", "~> 0.2.4"
end
diff --git a/ruby/lib/google/protobuf.rb b/ruby/lib/google/protobuf.rb
index 62bdd1bf..9b8d8231 100644
--- a/ruby/lib/google/protobuf.rb
+++ b/ruby/lib/google/protobuf.rb
@@ -45,7 +45,7 @@ if RUBY_PLATFORM == "java"
require 'google/protobuf_java'
else
begin
- require "google/#{RUBY_VERSION.sub(/\.\d$/, '')}/protobuf_c"
+ require "google/#{RUBY_VERSION.sub(/\.\d+$/, '')}/protobuf_c"
rescue LoadError
require 'google/protobuf_c'
end
diff --git a/ruby/pom.xml b/ruby/pom.xml
index 99e8449b..7b896137 100644
--- a/ruby/pom.xml
+++ b/ruby/pom.xml
@@ -86,7 +86,7 @@
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
- <version>3.0.0-beta-4</version>
+ <version>3.0.0</version>
</dependency>
</dependencies>
</project>
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
index 462f8a69..733ccfbc 100644
--- a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
+++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
@@ -41,6 +41,8 @@ import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
@@ -164,8 +166,21 @@ public class RubyMessage extends RubyObject {
*/
@JRubyMethod
public IRubyObject hash(ThreadContext context) {
- int hashCode = System.identityHashCode(this);
- return context.runtime.newFixnum(hashCode);
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ for (RubyMap map : maps.values()) {
+ digest.update((byte) map.hashCode());
+ }
+ for (RubyRepeatedField repeatedField : repeatedFields.values()) {
+ digest.update((byte) repeatedFields.hashCode());
+ }
+ for (IRubyObject field : fields.values()) {
+ digest.update((byte) field.hashCode());
+ }
+ return context.runtime.newString(new ByteList(digest.digest()));
+ } catch (NoSuchAlgorithmException ignore) {
+ return context.runtime.newFixnum(System.identityHashCode(this));
+ }
}
/*
diff --git a/ruby/tests/basic.rb b/ruby/tests/basic.rb
index 8b6d329e..989a047e 100644
--- a/ruby/tests/basic.rb
+++ b/ruby/tests/basic.rb
@@ -183,12 +183,15 @@ module BasicTest
def test_hash
m1 = TestMessage.new(:optional_int32 => 42)
- m2 = TestMessage.new(:optional_int32 => 102)
+ m2 = TestMessage.new(:optional_int32 => 102, repeated_string: ['please', 'work', 'ok?'])
+ m3 = TestMessage.new(:optional_int32 => 102, repeated_string: ['please', 'work', 'ok?'])
assert m1.hash != 0
assert m2.hash != 0
+ assert m3.hash != 0
# relying on the randomness here -- if hash function changes and we are
# unlucky enough to get a collision, then change the values above.
assert m1.hash != m2.hash
+ assert_equal m2.hash, m3.hash
end
def test_unknown_field_errors
diff --git a/ruby/travis-test.sh b/ruby/travis-test.sh
index 59e970a6..930165e6 100755
--- a/ruby/travis-test.sh
+++ b/ruby/travis-test.sh
@@ -8,14 +8,16 @@ test_version() {
if [ "$version" == "jruby-1.7" ] ; then
# No conformance tests yet -- JRuby is too broken to run them.
bash --login -c \
- "rvm install $version && rvm use $version && \
+ "rvm install $version && rvm use $version && rvm get head && \
which ruby && \
+ git clean -f && \
gem install bundler && bundle && \
rake test"
else
bash --login -c \
"rvm install $version && rvm use $version && \
which ruby && \
+ git clean -f && \
gem install bundler && bundle && \
rake test &&
cd ../conformance && make test_ruby"
diff --git a/src/Makefile.am b/src/Makefile.am
index f70e9550..8d9e07ab 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -61,121 +61,123 @@ CLEANFILES = $(protoc_outputs) unittest_proto_middleman \
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_atomicword_compat.h \
- google/protobuf/stubs/atomicops_internals_generic_gcc.h \
- google/protobuf/stubs/atomicops_internals_macosx.h \
- google/protobuf/stubs/atomicops_internals_mips_gcc.h \
- google/protobuf/stubs/atomicops_internals_pnacl.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 \
- google/protobuf/stubs/common.h \
- google/protobuf/stubs/fastmem.h \
- google/protobuf/stubs/hash.h \
- google/protobuf/stubs/logging.h \
- google/protobuf/stubs/macros.h \
- google/protobuf/stubs/mutex.h \
- 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 \
- google/protobuf/arena.h \
- google/protobuf/arenastring.h \
- google/protobuf/descriptor_database.h \
- google/protobuf/descriptor.h \
- google/protobuf/descriptor.pb.h \
- google/protobuf/duration.pb.h \
- google/protobuf/dynamic_message.h \
- google/protobuf/empty.pb.h \
- google/protobuf/extension_set.h \
- google/protobuf/field_mask.pb.h \
- google/protobuf/generated_enum_reflection.h \
- google/protobuf/generated_enum_util.h \
- google/protobuf/generated_message_reflection.h \
- google/protobuf/generated_message_util.h \
- google/protobuf/map_entry.h \
- google/protobuf/map_entry_lite.h \
- google/protobuf/map_field.h \
- google/protobuf/map_field_inl.h \
- google/protobuf/map_field_lite.h \
- google/protobuf/map.h \
- google/protobuf/map_type_handler.h \
- google/protobuf/message.h \
- google/protobuf/message_lite.h \
- google/protobuf/metadata.h \
- google/protobuf/reflection.h \
- google/protobuf/reflection_ops.h \
- google/protobuf/repeated_field.h \
- google/protobuf/service.h \
- google/protobuf/source_context.pb.h \
- google/protobuf/struct.pb.h \
- google/protobuf/text_format.h \
- google/protobuf/timestamp.pb.h \
- google/protobuf/type.pb.h \
- google/protobuf/unknown_field_set.h \
- google/protobuf/wire_format.h \
- google/protobuf/wire_format_lite.h \
- google/protobuf/wire_format_lite_inl.h \
- google/protobuf/wrappers.pb.h \
- google/protobuf/io/coded_stream.h \
- $(GZHEADERS) \
- google/protobuf/io/printer.h \
- google/protobuf/io/strtod.h \
- google/protobuf/io/tokenizer.h \
- google/protobuf/io/zero_copy_stream.h \
- google/protobuf/io/zero_copy_stream_impl.h \
- google/protobuf/io/zero_copy_stream_impl_lite.h \
- google/protobuf/compiler/code_generator.h \
- google/protobuf/compiler/command_line_interface.h \
- google/protobuf/compiler/importer.h \
- google/protobuf/compiler/parser.h \
- google/protobuf/compiler/plugin.h \
- google/protobuf/compiler/plugin.pb.h \
- google/protobuf/compiler/cpp/cpp_generator.h \
- google/protobuf/compiler/csharp/csharp_generator.h \
- 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/objectivec/objectivec_generator.h \
- google/protobuf/compiler/objectivec/objectivec_helpers.h \
- google/protobuf/compiler/python/python_generator.h \
- google/protobuf/compiler/ruby/ruby_generator.h \
- google/protobuf/util/type_resolver.h \
- google/protobuf/util/field_comparator.h \
- google/protobuf/util/field_mask_util.h \
- google/protobuf/util/json_util.h \
- google/protobuf/util/time_util.h \
- google/protobuf/util/type_resolver_util.h \
+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_atomicword_compat.h \
+ google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h \
+ google/protobuf/stubs/atomicops_internals_generic_gcc.h \
+ google/protobuf/stubs/atomicops_internals_macosx.h \
+ google/protobuf/stubs/atomicops_internals_mips_gcc.h \
+ google/protobuf/stubs/atomicops_internals_solaris.h \
+ google/protobuf/stubs/atomicops_internals_tsan.h \
+ 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 \
+ google/protobuf/stubs/common.h \
+ google/protobuf/stubs/fastmem.h \
+ google/protobuf/stubs/hash.h \
+ google/protobuf/stubs/logging.h \
+ google/protobuf/stubs/macros.h \
+ google/protobuf/stubs/mutex.h \
+ 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 \
+ google/protobuf/arena.h \
+ google/protobuf/arenastring.h \
+ google/protobuf/descriptor_database.h \
+ google/protobuf/descriptor.h \
+ google/protobuf/descriptor.pb.h \
+ google/protobuf/duration.pb.h \
+ google/protobuf/dynamic_message.h \
+ google/protobuf/empty.pb.h \
+ google/protobuf/extension_set.h \
+ google/protobuf/field_mask.pb.h \
+ google/protobuf/generated_enum_reflection.h \
+ google/protobuf/generated_enum_util.h \
+ google/protobuf/generated_message_reflection.h \
+ google/protobuf/generated_message_util.h \
+ google/protobuf/has_bits.h \
+ google/protobuf/map_entry.h \
+ google/protobuf/map_entry_lite.h \
+ google/protobuf/map_field.h \
+ google/protobuf/map_field_inl.h \
+ google/protobuf/map_field_lite.h \
+ google/protobuf/map.h \
+ google/protobuf/map_type_handler.h \
+ google/protobuf/message.h \
+ google/protobuf/message_lite.h \
+ google/protobuf/metadata.h \
+ google/protobuf/reflection.h \
+ google/protobuf/reflection_ops.h \
+ google/protobuf/repeated_field.h \
+ google/protobuf/service.h \
+ google/protobuf/source_context.pb.h \
+ google/protobuf/struct.pb.h \
+ google/protobuf/text_format.h \
+ google/protobuf/timestamp.pb.h \
+ google/protobuf/type.pb.h \
+ google/protobuf/unknown_field_set.h \
+ google/protobuf/wire_format.h \
+ google/protobuf/wire_format_lite.h \
+ google/protobuf/wire_format_lite_inl.h \
+ google/protobuf/wrappers.pb.h \
+ google/protobuf/io/coded_stream.h \
+ $(GZHEADERS) \
+ google/protobuf/io/printer.h \
+ google/protobuf/io/strtod.h \
+ google/protobuf/io/tokenizer.h \
+ google/protobuf/io/zero_copy_stream.h \
+ google/protobuf/io/zero_copy_stream_impl.h \
+ google/protobuf/io/zero_copy_stream_impl_lite.h \
+ google/protobuf/compiler/code_generator.h \
+ google/protobuf/compiler/command_line_interface.h \
+ google/protobuf/compiler/importer.h \
+ google/protobuf/compiler/parser.h \
+ google/protobuf/compiler/plugin.h \
+ google/protobuf/compiler/plugin.pb.h \
+ google/protobuf/compiler/cpp/cpp_generator.h \
+ google/protobuf/compiler/csharp/csharp_generator.h \
+ 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/objectivec/objectivec_generator.h \
+ google/protobuf/compiler/objectivec/objectivec_helpers.h \
+ google/protobuf/compiler/php/php_generator.h \
+ google/protobuf/compiler/python/python_generator.h \
+ google/protobuf/compiler/ruby/ruby_generator.h \
+ google/protobuf/util/type_resolver.h \
+ google/protobuf/util/field_comparator.h \
+ google/protobuf/util/field_mask_util.h \
+ google/protobuf/util/json_util.h \
+ google/protobuf/util/time_util.h \
+ google/protobuf/util/type_resolver_util.h \
google/protobuf/util/message_differencer.h
lib_LTLIBRARIES = libprotobuf-lite.la libprotobuf.la libprotoc.la
libprotobuf_lite_la_LIBADD = $(PTHREAD_LIBS)
-libprotobuf_lite_la_LDFLAGS = -version-info 10:0:0 -export-dynamic -no-undefined
+libprotobuf_lite_la_LDFLAGS = -version-info 11:0:0 -export-dynamic -no-undefined
libprotobuf_lite_la_SOURCES = \
google/protobuf/stubs/atomicops_internals_x86_gcc.cc \
google/protobuf/stubs/atomicops_internals_x86_msvc.cc \
@@ -216,7 +218,7 @@ libprotobuf_lite_la_SOURCES = \
google/protobuf/io/zero_copy_stream_impl_lite.cc
libprotobuf_la_LIBADD = $(PTHREAD_LIBS)
-libprotobuf_la_LDFLAGS = -version-info 10:0:0 -export-dynamic -no-undefined
+libprotobuf_la_LDFLAGS = -version-info 11:0:0 -export-dynamic -no-undefined
libprotobuf_la_SOURCES = \
$(libprotobuf_lite_la_SOURCES) \
google/protobuf/any.pb.cc \
@@ -300,7 +302,7 @@ libprotobuf_la_SOURCES = \
nodist_libprotobuf_la_SOURCES = $(nodist_libprotobuf_lite_la_SOURCES)
libprotoc_la_LIBADD = $(PTHREAD_LIBS) libprotobuf.la
-libprotoc_la_LDFLAGS = -version-info 10:0:0 -export-dynamic -no-undefined
+libprotoc_la_LDFLAGS = -version-info 11:0:0 -export-dynamic -no-undefined
libprotoc_la_SOURCES = \
google/protobuf/compiler/code_generator.cc \
google/protobuf/compiler/command_line_interface.cc \
@@ -443,6 +445,7 @@ libprotoc_la_SOURCES = \
google/protobuf/compiler/objectivec/objectivec_oneof.h \
google/protobuf/compiler/objectivec/objectivec_primitive_field.cc \
google/protobuf/compiler/objectivec/objectivec_primitive_field.h \
+ google/protobuf/compiler/php/php_generator.cc \
google/protobuf/compiler/python/python_generator.cc \
google/protobuf/compiler/ruby/ruby_generator.cc \
google/protobuf/compiler/csharp/csharp_doc_comment.cc \
@@ -524,8 +527,10 @@ protoc_inputs = \
google/protobuf/util/internal/testdata/field_mask.proto \
google/protobuf/util/internal/testdata/maps.proto \
google/protobuf/util/internal/testdata/oneofs.proto \
+ google/protobuf/util/internal/testdata/proto3.proto \
google/protobuf/util/internal/testdata/struct.proto \
google/protobuf/util/internal/testdata/timestamp_duration.proto \
+ google/protobuf/util/internal/testdata/wrappers.proto \
google/protobuf/util/json_format_proto3.proto \
google/protobuf/util/message_differencer_unittest.proto \
google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto
@@ -550,6 +555,7 @@ EXTRA_DIST = \
google/protobuf/testdata/text_format_unittest_extensions_data_pointy.txt \
google/protobuf/package_info.h \
google/protobuf/io/package_info.h \
+ google/protobuf/util/package_info.h \
google/protobuf/compiler/ruby/ruby_generated_code.proto \
google/protobuf/compiler/ruby/ruby_generated_code_pb.rb \
google/protobuf/compiler/package_info.h \
@@ -640,10 +646,14 @@ protoc_outputs = \
google/protobuf/util/internal/testdata/maps.pb.h \
google/protobuf/util/internal/testdata/oneofs.pb.cc \
google/protobuf/util/internal/testdata/oneofs.pb.h \
+ google/protobuf/util/internal/testdata/proto3.pb.cc \
+ google/protobuf/util/internal/testdata/proto3.pb.h \
google/protobuf/util/internal/testdata/struct.pb.cc \
google/protobuf/util/internal/testdata/struct.pb.h \
google/protobuf/util/internal/testdata/timestamp_duration.pb.cc \
google/protobuf/util/internal/testdata/timestamp_duration.pb.h \
+ google/protobuf/util/internal/testdata/wrappers.pb.cc \
+ google/protobuf/util/internal/testdata/wrappers.pb.h \
google/protobuf/util/json_format_proto3.pb.cc \
google/protobuf/util/json_format_proto3.pb.h \
google/protobuf/util/message_differencer_unittest.pb.cc \
diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc
index ccccc9c1..0df8d168 100644
--- a/src/google/protobuf/any.pb.cc
+++ b/src/google/protobuf/any.pb.cc
@@ -44,20 +44,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fany_2eproto() {
Any_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Any_descriptor_,
- Any::default_instance_,
+ Any::internal_default_instance(),
Any_offsets_,
-1,
-1,
-1,
sizeof(Any),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fany_2eproto);
}
@@ -66,37 +65,50 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Any_descriptor_, &Any::default_instance());
+ Any_descriptor_, Any::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto() {
- delete Any::default_instance_;
+ Any_default_instance_.Shutdown();
delete Any_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ ::google::protobuf::internal::GetEmptyString();
+ Any_default_instance_.DefaultConstruct();
+ Any_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\031google/protobuf/any.proto\022\017google.prot"
"obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002"
- " \001(\014Br\n\023com.google.protobufB\010AnyProtoP\001Z"
- "%github.com/golang/protobuf/ptypes/any\240\001"
- "\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes"
- "b\006proto3", 208);
+ " \001(\014Bo\n\023com.google.protobufB\010AnyProtoP\001Z"
+ "%github.com/golang/protobuf/ptypes/any\242\002"
+ "\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p"
+ "roto3", 205);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/any.proto", &protobuf_RegisterTypes);
- Any::default_instance_ = new Any();
- Any::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fany_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fany_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fany_2eproto() {
@@ -104,6 +116,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fany_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2fany_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
void Any::PackFrom(const ::google::protobuf::Message& message) {
@@ -126,12 +148,12 @@ const int Any::kValueFieldNumber;
Any::Any()
: ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Any)
}
void Any::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Any::Any(const Any& from)
@@ -139,16 +161,14 @@ Any::Any(const Any& from)
_internal_metadata_(NULL),
_any_metadata_(&type_url_, &value_) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Any)
}
void Any::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _cached_size_ = 0;
}
Any::~Any() {
@@ -159,8 +179,6 @@ Any::~Any() {
void Any::SharedDtor() {
type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void Any::SetCachedSize(int size) const {
@@ -174,11 +192,11 @@ const ::google::protobuf::Descriptor* Any::descriptor() {
}
const Any& Any::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
+ return *internal_default_instance();
}
-Any* Any::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Any> Any_default_instance_;
Any* Any::New(::google::protobuf::Arena* arena) const {
Any* n = new Any;
@@ -278,6 +296,7 @@ void Any::SerializeWithCachedSizes(
::google::protobuf::uint8* Any::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any)
// optional string type_url = 1;
if (this->type_url().size() > 0) {
@@ -301,9 +320,9 @@ void Any::SerializeWithCachedSizes(
return target;
}
-int Any::ByteSize() const {
+size_t Any::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Any)
- int total_size = 0;
+ size_t total_size = 0;
// optional string type_url = 1;
if (this->type_url().size() > 0) {
@@ -319,18 +338,17 @@ int Any::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Any::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Any)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Any* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Any* source =
::google::protobuf::internal::DynamicCastToGenerated<const Any>(
&from);
if (source == NULL) {
@@ -338,15 +356,21 @@ void Any::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Any)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Any::MergeFrom(const Any& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Any::UnsafeMergeFrom(const Any& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.type_url().size() > 0) {
type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_);
@@ -368,7 +392,7 @@ void Any::CopyFrom(const Any& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Any)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Any::IsInitialized() const {
@@ -402,37 +426,37 @@ void Any::InternalSwap(Any* other) {
void Any::clear_type_url() {
type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Any::type_url() const {
+const ::std::string& Any::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.type_url)
return type_url_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Any::set_type_url(const ::std::string& value) {
+void Any::set_type_url(const ::std::string& value) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.type_url)
}
- void Any::set_type_url(const char* value) {
+void Any::set_type_url(const char* value) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url)
}
- void Any::set_type_url(const char* value, size_t size) {
+void Any::set_type_url(const char* value, size_t size) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url)
}
- ::std::string* Any::mutable_type_url() {
+::std::string* Any::mutable_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Any.type_url)
return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Any::release_type_url() {
+::std::string* Any::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.type_url)
return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Any::set_allocated_type_url(::std::string* type_url) {
+void Any::set_allocated_type_url(::std::string* type_url) {
if (type_url != NULL) {
} else {
@@ -446,37 +470,37 @@ void Any::clear_type_url() {
void Any::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Any::value() const {
+const ::std::string& Any::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.value)
return value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Any::set_value(const ::std::string& value) {
+void Any::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.value)
}
- void Any::set_value(const char* value) {
+void Any::set_value(const char* value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.value)
}
- void Any::set_value(const void* value, size_t size) {
+void Any::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value)
}
- ::std::string* Any::mutable_value() {
+::std::string* Any::mutable_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Any.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Any::release_value() {
+::std::string* Any::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Any::set_allocated_value(::std::string* value) {
+void Any::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
@@ -486,6 +510,9 @@ void Any::clear_value() {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
+inline const Any* Any::internal_default_instance() {
+ return &Any_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h
index d8cbee2d..0641e244 100644
--- a/src/google/protobuf/any.pb.h
+++ b/src/google/protobuf/any.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -35,6 +35,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fany_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto();
@@ -57,6 +58,8 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
static const ::google::protobuf::Descriptor* descriptor();
static const Any& default_instance();
+ static const Any* internal_default_instance();
+
// implements Any -----------------------------------------------
void PackFrom(const ::google::protobuf::Message& message);
@@ -81,7 +84,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -97,6 +100,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Any* other);
+ void UnsafeMergeFrom(const Any& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -138,18 +142,19 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
::google::protobuf::internal::ArenaStringPtr type_url_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fany_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fany_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fany_2eproto();
void InitAsDefaultInstance();
- static Any* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Any> Any_default_instance_;
+
// ===================================================================
@@ -246,6 +251,9 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
+inline const Any* Any::internal_default_instance() {
+ return &Any_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/any.proto b/src/google/protobuf/any.proto
index 81dcf46c..9bd3f50a 100644
--- a/src/google/protobuf/any.proto
+++ b/src/google/protobuf/any.proto
@@ -37,7 +37,6 @@ option go_package = "github.com/golang/protobuf/ptypes/any";
option java_package = "com.google.protobuf";
option java_outer_classname = "AnyProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// `Any` contains an arbitrary serialized protocol buffer message along with a
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc
index cfb30786..35139faf 100644
--- a/src/google/protobuf/api.pb.cc
+++ b/src/google/protobuf/api.pb.cc
@@ -55,14 +55,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto() {
Api_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Api_descriptor_,
- Api::default_instance_,
+ Api::internal_default_instance(),
Api_offsets_,
-1,
-1,
-1,
sizeof(Api),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Api, _internal_metadata_));
Method_descriptor_ = file->message_type(1);
static const int Method_offsets_[7] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, name_),
@@ -76,14 +75,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto() {
Method_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Method_descriptor_,
- Method::default_instance_,
+ Method::internal_default_instance(),
Method_offsets_,
-1,
-1,
-1,
sizeof(Method),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Method, _internal_metadata_));
Mixin_descriptor_ = file->message_type(2);
static const int Mixin_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, name_),
@@ -92,20 +90,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto() {
Mixin_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Mixin_descriptor_,
- Mixin::default_instance_,
+ Mixin::internal_default_instance(),
Mixin_offsets_,
-1,
-1,
-1,
sizeof(Mixin),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Mixin, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto);
}
@@ -114,33 +111,49 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Api_descriptor_, &Api::default_instance());
+ Api_descriptor_, Api::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Method_descriptor_, &Method::default_instance());
+ Method_descriptor_, Method::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Mixin_descriptor_, &Mixin::default_instance());
+ Mixin_descriptor_, Mixin::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto() {
- delete Api::default_instance_;
+ Api_default_instance_.Shutdown();
delete Api_reflection_;
- delete Method::default_instance_;
+ Method_default_instance_.Shutdown();
delete Method_reflection_;
- delete Mixin::default_instance_;
+ Mixin_default_instance_.Shutdown();
delete Mixin_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ ::google::protobuf::internal::GetEmptyString();
+ Api_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ Method_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ Mixin_default_instance_.DefaultConstruct();
+ Api_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Method_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Mixin_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\031google/protobuf/api.proto\022\017google.prot"
"obuf\032$google/protobuf/source_context.pro"
@@ -157,20 +170,21 @@ void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto() {
"esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013"
"2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001("
"\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n"
- "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBK\n\023com.google.pr"
- "otobufB\010ApiProtoP\001\240\001\001\242\002\003GPB\252\002\036Google.Pro"
- "tobuf.WellKnownTypesb\006proto3", 708);
+ "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBH\n\023com.google.pr"
+ "otobufB\010ApiProtoP\001\242\002\003GPB\252\002\036Google.Protob"
+ "uf.WellKnownTypesb\006proto3", 705);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/api.proto", &protobuf_RegisterTypes);
- Api::default_instance_ = new Api();
- Method::default_instance_ = new Method();
- Mixin::default_instance_ = new Mixin();
- Api::default_instance_->InitAsDefaultInstance();
- Method::default_instance_->InitAsDefaultInstance();
- Mixin::default_instance_->InitAsDefaultInstance();
+ ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fapi_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fapi_2eproto() {
@@ -178,6 +192,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fapi_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2fapi_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -192,31 +216,30 @@ const int Api::kSyntaxFieldNumber;
Api::Api()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Api)
}
void Api::InitAsDefaultInstance() {
- _is_default_instance_ = true;
- source_context_ = const_cast< ::google::protobuf::SourceContext*>(&::google::protobuf::SourceContext::default_instance());
+ source_context_ = const_cast< ::google::protobuf::SourceContext*>(
+ ::google::protobuf::SourceContext::internal_default_instance());
}
Api::Api(const Api& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Api)
}
void Api::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
source_context_ = NULL;
syntax_ = 0;
+ _cached_size_ = 0;
}
Api::~Api() {
@@ -227,7 +250,7 @@ Api::~Api() {
void Api::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &Api_default_instance_.get()) {
delete source_context_;
}
}
@@ -243,11 +266,11 @@ const ::google::protobuf::Descriptor* Api::descriptor() {
}
const Api& Api::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ return *internal_default_instance();
}
-Api* Api::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Api> Api_default_instance_;
Api* Api::New(::google::protobuf::Arena* arena) const {
Api* n = new Api;
@@ -470,6 +493,7 @@ void Api::SerializeWithCachedSizes(
::google::protobuf::uint8* Api::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Api)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -531,9 +555,9 @@ void Api::SerializeWithCachedSizes(
return target;
}
-int Api::ByteSize() const {
+size_t Api::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Api)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -563,41 +587,49 @@ int Api::ByteSize() const {
}
// repeated .google.protobuf.Method methods = 2;
- total_size += 1 * this->methods_size();
- for (int i = 0; i < this->methods_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->methods(i));
+ {
+ unsigned int count = this->methods_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->methods(i));
+ }
}
// repeated .google.protobuf.Option options = 3;
- total_size += 1 * this->options_size();
- for (int i = 0; i < this->options_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ {
+ unsigned int count = this->options_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->options(i));
+ }
}
// repeated .google.protobuf.Mixin mixins = 6;
- total_size += 1 * this->mixins_size();
- for (int i = 0; i < this->mixins_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->mixins(i));
+ {
+ unsigned int count = this->mixins_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->mixins(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Api::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Api)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Api* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Api* source =
::google::protobuf::internal::DynamicCastToGenerated<const Api>(
&from);
if (source == NULL) {
@@ -605,15 +637,21 @@ void Api::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Api)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Api::MergeFrom(const Api& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Api)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Api::UnsafeMergeFrom(const Api& from) {
+ GOOGLE_DCHECK(&from != this);
methods_.MergeFrom(from.methods_);
options_.MergeFrom(from.options_);
mixins_.MergeFrom(from.mixins_);
@@ -644,7 +682,7 @@ void Api::CopyFrom(const Api& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Api)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Api::IsInitialized() const {
@@ -683,37 +721,37 @@ void Api::InternalSwap(Api* other) {
void Api::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Api::name() const {
+const ::std::string& Api::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Api::set_name(const ::std::string& value) {
+void Api::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Api.name)
}
- void Api::set_name(const char* value) {
+void Api::set_name(const char* value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Api.name)
}
- void Api::set_name(const char* value, size_t size) {
+void Api::set_name(const char* value, size_t size) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.name)
}
- ::std::string* Api::mutable_name() {
+::std::string* Api::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Api::release_name() {
+::std::string* Api::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.name)
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Api::set_allocated_name(::std::string* name) {
+void Api::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
@@ -787,37 +825,37 @@ Api::options() const {
void Api::clear_version() {
version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Api::version() const {
+const ::std::string& Api::version() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.version)
return version_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Api::set_version(const ::std::string& value) {
+void Api::set_version(const ::std::string& value) {
version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Api.version)
}
- void Api::set_version(const char* value) {
+void Api::set_version(const char* value) {
version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Api.version)
}
- void Api::set_version(const char* value, size_t size) {
+void Api::set_version(const char* value, size_t size) {
version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.version)
}
- ::std::string* Api::mutable_version() {
+::std::string* Api::mutable_version() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.version)
return version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Api::release_version() {
+::std::string* Api::release_version() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.version)
return version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Api::set_allocated_version(::std::string* version) {
+void Api::set_allocated_version(::std::string* version) {
if (version != NULL) {
} else {
@@ -829,7 +867,7 @@ void Api::clear_version() {
// optional .google.protobuf.SourceContext source_context = 5;
bool Api::has_source_context() const {
- return !_is_default_instance_ && source_context_ != NULL;
+ return this != internal_default_instance() && source_context_ != NULL;
}
void Api::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
@@ -837,7 +875,8 @@ void Api::clear_source_context() {
}
const ::google::protobuf::SourceContext& Api::source_context() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.source_context)
- return source_context_ != NULL ? *source_context_ : *default_instance_->source_context_;
+ return source_context_ != NULL ? *source_context_
+ : *::google::protobuf::SourceContext::internal_default_instance();
}
::google::protobuf::SourceContext* Api::mutable_source_context() {
@@ -899,16 +938,19 @@ Api::mixins() const {
void Api::clear_syntax() {
syntax_ = 0;
}
- ::google::protobuf::Syntax Api::syntax() const {
+::google::protobuf::Syntax Api::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.syntax)
return static_cast< ::google::protobuf::Syntax >(syntax_);
}
- void Api::set_syntax(::google::protobuf::Syntax value) {
+void Api::set_syntax(::google::protobuf::Syntax value) {
syntax_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Api.syntax)
}
+inline const Api* Api::internal_default_instance() {
+ return &Api_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -925,32 +967,29 @@ const int Method::kSyntaxFieldNumber;
Method::Method()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Method)
}
void Method::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Method::Method(const Method& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Method)
}
void Method::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- request_streaming_ = false;
response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- response_streaming_ = false;
- syntax_ = 0;
+ ::memset(&request_streaming_, 0, reinterpret_cast<char*>(&syntax_) -
+ reinterpret_cast<char*>(&request_streaming_) + sizeof(syntax_));
+ _cached_size_ = 0;
}
Method::~Method() {
@@ -962,8 +1001,6 @@ void Method::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
request_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
response_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void Method::SetCachedSize(int size) const {
@@ -977,11 +1014,11 @@ const ::google::protobuf::Descriptor* Method::descriptor() {
}
const Method& Method::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ return *internal_default_instance();
}
-Method* Method::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Method> Method_default_instance_;
Method* Method::New(::google::protobuf::Arena* arena) const {
Method* n = new Method;
@@ -1005,7 +1042,7 @@ void Method::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -1067,10 +1104,10 @@ bool Method::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_request_streaming:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &request_streaming_)));
-
} else {
goto handle_unusual;
}
@@ -1099,10 +1136,10 @@ bool Method::MergePartialFromCodedStream(
case 5: {
if (tag == 40) {
parse_response_streaming:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &response_streaming_)));
-
} else {
goto handle_unusual;
}
@@ -1224,6 +1261,7 @@ void Method::SerializeWithCachedSizes(
::google::protobuf::uint8* Method::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Method)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -1285,9 +1323,9 @@ void Method::SerializeWithCachedSizes(
return target;
}
-int Method::ByteSize() const {
+size_t Method::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Method)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -1327,25 +1365,27 @@ int Method::ByteSize() const {
}
// repeated .google.protobuf.Option options = 6;
- total_size += 1 * this->options_size();
- for (int i = 0; i < this->options_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ {
+ unsigned int count = this->options_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->options(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Method::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Method)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Method* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Method* source =
::google::protobuf::internal::DynamicCastToGenerated<const Method>(
&from);
if (source == NULL) {
@@ -1353,15 +1393,21 @@ void Method::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Method)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Method::MergeFrom(const Method& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Method)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Method::UnsafeMergeFrom(const Method& from) {
+ GOOGLE_DCHECK(&from != this);
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
@@ -1397,7 +1443,7 @@ void Method::CopyFrom(const Method& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Method)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Method::IsInitialized() const {
@@ -1436,37 +1482,37 @@ void Method::InternalSwap(Method* other) {
void Method::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Method::name() const {
+const ::std::string& Method::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Method::set_name(const ::std::string& value) {
+void Method::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Method.name)
}
- void Method::set_name(const char* value) {
+void Method::set_name(const char* value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.name)
}
- void Method::set_name(const char* value, size_t size) {
+void Method::set_name(const char* value, size_t size) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.name)
}
- ::std::string* Method::mutable_name() {
+::std::string* Method::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Method.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Method::release_name() {
+::std::string* Method::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Method.name)
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Method::set_allocated_name(::std::string* name) {
+void Method::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
@@ -1480,37 +1526,37 @@ void Method::clear_name() {
void Method::clear_request_type_url() {
request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Method::request_type_url() const {
+const ::std::string& Method::request_type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.request_type_url)
return request_type_url_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Method::set_request_type_url(const ::std::string& value) {
+void Method::set_request_type_url(const ::std::string& value) {
request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Method.request_type_url)
}
- void Method::set_request_type_url(const char* value) {
+void Method::set_request_type_url(const char* value) {
request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.request_type_url)
}
- void Method::set_request_type_url(const char* value, size_t size) {
+void Method::set_request_type_url(const char* value, size_t size) {
request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.request_type_url)
}
- ::std::string* Method::mutable_request_type_url() {
+::std::string* Method::mutable_request_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Method.request_type_url)
return request_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Method::release_request_type_url() {
+::std::string* Method::release_request_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url)
return request_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Method::set_allocated_request_type_url(::std::string* request_type_url) {
+void Method::set_allocated_request_type_url(::std::string* request_type_url) {
if (request_type_url != NULL) {
} else {
@@ -1524,11 +1570,11 @@ void Method::clear_request_type_url() {
void Method::clear_request_streaming() {
request_streaming_ = false;
}
- bool Method::request_streaming() const {
+bool Method::request_streaming() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.request_streaming)
return request_streaming_;
}
- void Method::set_request_streaming(bool value) {
+void Method::set_request_streaming(bool value) {
request_streaming_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Method.request_streaming)
@@ -1538,37 +1584,37 @@ void Method::clear_request_streaming() {
void Method::clear_response_type_url() {
response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Method::response_type_url() const {
+const ::std::string& Method::response_type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.response_type_url)
return response_type_url_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Method::set_response_type_url(const ::std::string& value) {
+void Method::set_response_type_url(const ::std::string& value) {
response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Method.response_type_url)
}
- void Method::set_response_type_url(const char* value) {
+void Method::set_response_type_url(const char* value) {
response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Method.response_type_url)
}
- void Method::set_response_type_url(const char* value, size_t size) {
+void Method::set_response_type_url(const char* value, size_t size) {
response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.response_type_url)
}
- ::std::string* Method::mutable_response_type_url() {
+::std::string* Method::mutable_response_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Method.response_type_url)
return response_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Method::release_response_type_url() {
+::std::string* Method::release_response_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url)
return response_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Method::set_allocated_response_type_url(::std::string* response_type_url) {
+void Method::set_allocated_response_type_url(::std::string* response_type_url) {
if (response_type_url != NULL) {
} else {
@@ -1582,11 +1628,11 @@ void Method::clear_response_type_url() {
void Method::clear_response_streaming() {
response_streaming_ = false;
}
- bool Method::response_streaming() const {
+bool Method::response_streaming() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.response_streaming)
return response_streaming_;
}
- void Method::set_response_streaming(bool value) {
+void Method::set_response_streaming(bool value) {
response_streaming_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Method.response_streaming)
@@ -1626,16 +1672,19 @@ Method::options() const {
void Method::clear_syntax() {
syntax_ = 0;
}
- ::google::protobuf::Syntax Method::syntax() const {
+::google::protobuf::Syntax Method::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.syntax)
return static_cast< ::google::protobuf::Syntax >(syntax_);
}
- void Method::set_syntax(::google::protobuf::Syntax value) {
+void Method::set_syntax(::google::protobuf::Syntax value) {
syntax_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Method.syntax)
}
+inline const Method* Method::internal_default_instance() {
+ return &Method_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1647,28 +1696,26 @@ const int Mixin::kRootFieldNumber;
Mixin::Mixin()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Mixin)
}
void Mixin::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Mixin::Mixin(const Mixin& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin)
}
void Mixin::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _cached_size_ = 0;
}
Mixin::~Mixin() {
@@ -1679,8 +1726,6 @@ Mixin::~Mixin() {
void Mixin::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void Mixin::SetCachedSize(int size) const {
@@ -1694,11 +1739,11 @@ const ::google::protobuf::Descriptor* Mixin::descriptor() {
}
const Mixin& Mixin::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
+ return *internal_default_instance();
}
-Mixin* Mixin::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Mixin> Mixin_default_instance_;
Mixin* Mixin::New(::google::protobuf::Arena* arena) const {
Mixin* n = new Mixin;
@@ -1806,6 +1851,7 @@ void Mixin::SerializeWithCachedSizes(
::google::protobuf::uint8* Mixin::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Mixin)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -1833,9 +1879,9 @@ void Mixin::SerializeWithCachedSizes(
return target;
}
-int Mixin::ByteSize() const {
+size_t Mixin::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Mixin)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -1851,18 +1897,17 @@ int Mixin::ByteSize() const {
this->root());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Mixin::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Mixin)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Mixin* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Mixin* source =
::google::protobuf::internal::DynamicCastToGenerated<const Mixin>(
&from);
if (source == NULL) {
@@ -1870,15 +1915,21 @@ void Mixin::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Mixin)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Mixin::MergeFrom(const Mixin& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Mixin)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Mixin::UnsafeMergeFrom(const Mixin& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
@@ -1900,7 +1951,7 @@ void Mixin::CopyFrom(const Mixin& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Mixin)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Mixin::IsInitialized() const {
@@ -1934,37 +1985,37 @@ void Mixin::InternalSwap(Mixin* other) {
void Mixin::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Mixin::name() const {
+const ::std::string& Mixin::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Mixin.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Mixin::set_name(const ::std::string& value) {
+void Mixin::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Mixin.name)
}
- void Mixin::set_name(const char* value) {
+void Mixin::set_name(const char* value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.name)
}
- void Mixin::set_name(const char* value, size_t size) {
+void Mixin::set_name(const char* value, size_t size) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.name)
}
- ::std::string* Mixin::mutable_name() {
+::std::string* Mixin::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Mixin::release_name() {
+::std::string* Mixin::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Mixin.name)
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Mixin::set_allocated_name(::std::string* name) {
+void Mixin::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
@@ -1978,37 +2029,37 @@ void Mixin::clear_name() {
void Mixin::clear_root() {
root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& Mixin::root() const {
+const ::std::string& Mixin::root() const {
// @@protoc_insertion_point(field_get:google.protobuf.Mixin.root)
return root_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Mixin::set_root(const ::std::string& value) {
+void Mixin::set_root(const ::std::string& value) {
root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Mixin.root)
}
- void Mixin::set_root(const char* value) {
+void Mixin::set_root(const char* value) {
root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.root)
}
- void Mixin::set_root(const char* value, size_t size) {
+void Mixin::set_root(const char* value, size_t size) {
root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.root)
}
- ::std::string* Mixin::mutable_root() {
+::std::string* Mixin::mutable_root() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.root)
return root_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Mixin::release_root() {
+::std::string* Mixin::release_root() {
// @@protoc_insertion_point(field_release:google.protobuf.Mixin.root)
return root_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Mixin::set_allocated_root(::std::string* root) {
+void Mixin::set_allocated_root(::std::string* root) {
if (root != NULL) {
} else {
@@ -2018,6 +2069,9 @@ void Mixin::clear_root() {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
}
+inline const Mixin* Mixin::internal_default_instance() {
+ return &Mixin_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h
index c9ec923a..94102863 100644
--- a/src/google/protobuf/api.pb.h
+++ b/src/google/protobuf/api.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -36,6 +36,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
@@ -60,6 +61,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
static const ::google::protobuf::Descriptor* descriptor();
static const Api& default_instance();
+ static const Api* internal_default_instance();
+
void Swap(Api* other);
// implements Message ----------------------------------------------
@@ -74,7 +77,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -90,6 +93,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Api* other);
+ void UnsafeMergeFrom(const Api& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -182,22 +186,23 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
- ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Method > methods_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin > mixins_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr version_;
::google::protobuf::SourceContext* source_context_;
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin > mixins_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
void InitAsDefaultInstance();
- static Api* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Api> Api_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ {
@@ -215,6 +220,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
static const ::google::protobuf::Descriptor* descriptor();
static const Method& default_instance();
+ static const Method* internal_default_instance();
+
void Swap(Method* other);
// implements Message ----------------------------------------------
@@ -229,7 +236,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -245,6 +252,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Method* other);
+ void UnsafeMergeFrom(const Method& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -327,22 +335,23 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr request_type_url_;
::google::protobuf::internal::ArenaStringPtr response_type_url_;
bool request_streaming_;
bool response_streaming_;
int syntax_;
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
void InitAsDefaultInstance();
- static Method* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Method> Method_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ {
@@ -360,6 +369,8 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
static const ::google::protobuf::Descriptor* descriptor();
static const Mixin& default_instance();
+ static const Mixin* internal_default_instance();
+
void Swap(Mixin* other);
// implements Message ----------------------------------------------
@@ -374,7 +385,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -390,6 +401,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Mixin* other);
+ void UnsafeMergeFrom(const Mixin& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -431,17 +443,18 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr root_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fapi_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fapi_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fapi_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fapi_2eproto();
void InitAsDefaultInstance();
- static Mixin* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Mixin> Mixin_default_instance_;
+
// ===================================================================
@@ -600,7 +613,7 @@ inline void Api::set_allocated_version(::std::string* version) {
// optional .google.protobuf.SourceContext source_context = 5;
inline bool Api::has_source_context() const {
- return !_is_default_instance_ && source_context_ != NULL;
+ return this != internal_default_instance() && source_context_ != NULL;
}
inline void Api::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
@@ -608,7 +621,8 @@ inline void Api::clear_source_context() {
}
inline const ::google::protobuf::SourceContext& Api::source_context() const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.source_context)
- return source_context_ != NULL ? *source_context_ : *default_instance_->source_context_;
+ return source_context_ != NULL ? *source_context_
+ : *::google::protobuf::SourceContext::internal_default_instance();
}
inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
@@ -680,6 +694,9 @@ inline void Api::set_syntax(::google::protobuf::Syntax value) {
// @@protoc_insertion_point(field_set:google.protobuf.Api.syntax)
}
+inline const Api* Api::internal_default_instance() {
+ return &Api_default_instance_.get();
+}
// -------------------------------------------------------------------
// Method
@@ -888,6 +905,9 @@ inline void Method::set_syntax(::google::protobuf::Syntax value) {
// @@protoc_insertion_point(field_set:google.protobuf.Method.syntax)
}
+inline const Method* Method::internal_default_instance() {
+ return &Method_default_instance_.get();
+}
// -------------------------------------------------------------------
// Mixin
@@ -980,6 +1000,9 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
}
+inline const Mixin* Mixin::internal_default_instance() {
+ return &Mixin_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
diff --git a/src/google/protobuf/api.proto b/src/google/protobuf/api.proto
index dbe87b8f..bbbe9833 100644
--- a/src/google/protobuf/api.proto
+++ b/src/google/protobuf/api.proto
@@ -39,7 +39,6 @@ option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option java_package = "com.google.protobuf";
option java_outer_classname = "ApiProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// Api is a light-weight descriptor for a protocol buffer service.
diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc
index 78e20946..aa4e587c 100755
--- a/src/google/protobuf/arena.cc
+++ b/src/google/protobuf/arena.cc
@@ -30,6 +30,9 @@
#include <google/protobuf/arena.h>
+#include <algorithm>
+#include <limits>
+
#ifdef ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
@@ -125,10 +128,9 @@ Arena::Block* Arena::NewBlock(void* me, Block* my_last_block, size_t n,
} else {
size = start_block_size;
}
- if (n > size - kHeaderSize) {
- // TODO(sanjay): Check if n + kHeaderSize would overflow
- size = kHeaderSize + n;
- }
+ // Verify that n + kHeaderSize won't overflow.
+ GOOGLE_CHECK_LE(n, std::numeric_limits<size_t>::max() - kHeaderSize);
+ size = std::max(size, kHeaderSize + n);
Block* b = reinterpret_cast<Block*>(options_.block_alloc(size));
b->pos = kHeaderSize + n;
diff --git a/src/google/protobuf/arena.h b/src/google/protobuf/arena.h
index 58b1e126..87066507 100644
--- a/src/google/protobuf/arena.h
+++ b/src/google/protobuf/arena.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// This file defines an Arena allocator for better allocation performance.
+
#ifndef GOOGLE_PROTOBUF_ARENA_H__
#define GOOGLE_PROTOBUF_ARENA_H__
@@ -77,8 +79,13 @@ template<typename T> void arena_destruct_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 */) {
- free(object);
+inline void arena_free(void* object, size_t size) {
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ ::operator delete(object, size);
+#else
+ (void)size;
+ ::operator delete(object);
+#endif
}
} // namespace internal
@@ -142,7 +149,7 @@ struct ArenaOptions {
max_block_size(kDefaultMaxBlockSize),
initial_block(NULL),
initial_block_size(0),
- block_alloc(&malloc),
+ block_alloc(&::operator new),
block_dealloc(&internal::arena_free),
on_arena_init(NULL),
on_arena_reset(NULL),
@@ -211,12 +218,10 @@ struct ArenaOptions {
//
// This protocol is implemented by all arena-enabled proto2 message classes as
// well as RepeatedPtrField.
-
-#if __cplusplus >= 201103L
-class LIBPROTOBUF_EXPORT Arena final {
-#else
+//
+// Do NOT subclass Arena. This class will be marked as final when C++11 is
+// enabled.
class LIBPROTOBUF_EXPORT Arena {
-#endif
public:
// Arena constructor taking custom options. See ArenaOptions below for
// descriptions of the options available.
@@ -454,7 +459,7 @@ class LIBPROTOBUF_EXPORT Arena {
// Combines SpaceAllocated and SpaceUsed. Returns a pair of
// <space_allocated, space_used>.
- GOOGLE_ATTRIBUTE_NOINLINE pair<uint64, uint64> SpaceAllocatedAndUsed() const;
+ GOOGLE_ATTRIBUTE_NOINLINE std::pair<uint64, uint64> SpaceAllocatedAndUsed() const;
// Frees all storage allocated by this arena after calling destructors
// registered with OwnDestructor() and freeing objects registered with Own().
@@ -608,6 +613,7 @@ class LIBPROTOBUF_EXPORT Arena {
const T>(static_cast<const T*>(0))) == sizeof(char) ||
google::protobuf::internal::has_trivial_destructor<T>::value> {};
+ private:
// CreateMessage<T> requires that T supports arenas, but this private method
// works whether or not T supports arenas. These are not exposed to user code
// as it can cause confusing API usages, and end up having double free in
diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc
index 5f33e939..35d00463 100644
--- a/src/google/protobuf/arena_unittest.cc
+++ b/src/google/protobuf/arena_unittest.cc
@@ -151,8 +151,6 @@ class MustBeConstructedWithOneThroughEight {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughEight);
};
-} // namespace
-
TEST(ArenaTest, ArenaConstructable) {
EXPECT_TRUE(Arena::is_arena_constructable<TestAllTypes>::type::value);
EXPECT_TRUE(Arena::is_arena_constructable<const TestAllTypes>::type::value);
@@ -893,6 +891,24 @@ TEST(ArenaTest, UnsafeArenaRelease) {
delete s;
}
+TEST(ArenaTest, OneofMerge) {
+ Arena arena;
+ TestAllTypes* message0 = Arena::CreateMessage<TestAllTypes>(&arena);
+ TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&arena);
+
+ message0->unsafe_arena_set_allocated_oneof_string(new string("x"));
+ ASSERT_TRUE(message0->has_oneof_string());
+ message1->unsafe_arena_set_allocated_oneof_string(new string("y"));
+ ASSERT_TRUE(message1->has_oneof_string());
+ EXPECT_EQ("x", message0->oneof_string());
+ EXPECT_EQ("y", message1->oneof_string());
+ message0->MergeFrom(*message1);
+ EXPECT_EQ("y", message0->oneof_string());
+ EXPECT_EQ("y", message1->oneof_string());
+ delete message0->unsafe_arena_release_oneof_string();
+ delete message1->unsafe_arena_release_oneof_string();
+}
+
TEST(ArenaTest, ArenaOneofReflection) {
Arena arena;
TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
@@ -923,7 +939,6 @@ TEST(ArenaTest, ArenaOneofReflection) {
delete submsg;
}
-namespace {
void TestSwapRepeatedField(Arena* arena1, Arena* arena2) {
// Test "safe" (copying) semantics for direct Swap() on RepeatedPtrField
// between arenas.
@@ -962,7 +977,6 @@ void TestSwapRepeatedField(Arena* arena1, Arena* arena2) {
EXPECT_EQ(i, field2.Get(i).optional_int32());
}
}
-} // namespace
TEST(ArenaTest, SwapRepeatedField) {
Arena arena;
@@ -1104,8 +1118,6 @@ TEST(ArenaTest, MutableMessageReflection) {
#endif // !GOOGLE_PROTOBUF_NO_RTTI
-namespace {
-
void FillArenaAwareFields(TestAllTypes* message) {
string test_string = "hello world";
message->set_optional_int32(42);
@@ -1124,8 +1136,6 @@ void FillArenaAwareFields(TestAllTypes* message) {
message->mutable_optional_lazy_message()->set_bb(42);
}
-}
-
// Test: no allocations occur on heap while touching all supported field types.
TEST(ArenaTest, NoHeapAllocationsTest) {
// Allocate a large initial block to avoid mallocs during hooked test.
@@ -1196,9 +1206,7 @@ TEST(ArenaTest, RepeatedFieldWithNonPODType) {
}
// Align n to next multiple of 8
-namespace {
uint64 Align8(uint64 n) { return (n + 7) & -8; }
-} // namespace
TEST(ArenaTest, SpaceAllocated_and_Used) {
ArenaOptions options;
@@ -1249,6 +1257,22 @@ TEST(ArenaTest, Alignment) {
}
}
+TEST(ArenaTest, BlockSizeSmallerThanAllocation) {
+ for (size_t i = 0; i <= 8; ++i) {
+ ::google::protobuf::ArenaOptions opt;
+ opt.start_block_size = opt.max_block_size = i;
+ ::google::protobuf::Arena arena(opt);
+
+ *::google::protobuf::Arena::Create<int64>(&arena) = 42;
+ EXPECT_GE(arena.SpaceAllocated(), 8);
+ EXPECT_EQ(8, arena.SpaceUsed());
+
+ *::google::protobuf::Arena::Create<int64>(&arena) = 42;
+ EXPECT_GE(arena.SpaceAllocated(), 16);
+ EXPECT_EQ(16, arena.SpaceUsed());
+ }
+}
+
TEST(ArenaTest, GetArenaShouldReturnTheArenaForArenaAllocatedMessages) {
::google::protobuf::Arena arena;
ArenaMessage* message = Arena::CreateMessage<ArenaMessage>(&arena);
@@ -1349,5 +1373,7 @@ TEST(ArenaTest, ArenaHooksSanity) {
EXPECT_EQ(1, ArenaHooksTestUtil::num_destruct);
}
+
+} // namespace
} // namespace protobuf
} // namespace google
diff --git a/src/google/protobuf/compiler/code_generator.cc b/src/google/protobuf/compiler/code_generator.cc
index 473eb4e6..f6ff1e5d 100644
--- a/src/google/protobuf/compiler/code_generator.cc
+++ b/src/google/protobuf/compiler/code_generator.cc
@@ -36,6 +36,7 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
+#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -43,6 +44,33 @@ namespace protobuf {
namespace compiler {
CodeGenerator::~CodeGenerator() {}
+
+bool CodeGenerator::GenerateAll(
+ const vector<const FileDescriptor*>& files,
+ const string& parameter,
+ GeneratorContext* generator_context,
+ string* error) const {
+ // Default implemenation is just to call the per file method, and prefix any
+ // error string with the file to provide context.
+ bool succeeded = true;
+ for (int i = 0; i < files.size(); i++) {
+ const FileDescriptor* file = files[i];
+ succeeded = Generate(file, parameter, generator_context, error);
+ if (!succeeded && error && error->empty()) {
+ *error = "Code generator returned false but provided no error "
+ "description.";
+ }
+ if (error && !error->empty()) {
+ *error = file->name() + ": " + *error;
+ break;
+ }
+ if (!succeeded) {
+ break;
+ }
+ }
+ return succeeded;
+}
+
GeneratorContext::~GeneratorContext() {}
io::ZeroCopyOutputStream*
diff --git a/src/google/protobuf/compiler/code_generator.h b/src/google/protobuf/compiler/code_generator.h
index b989f151..642bbfad 100644
--- a/src/google/protobuf/compiler/code_generator.h
+++ b/src/google/protobuf/compiler/code_generator.h
@@ -66,11 +66,11 @@ class LIBPROTOC_EXPORT CodeGenerator {
// Generates code for the given proto file, generating one or more files in
// the given output directory.
//
- // A parameter to be passed to the generator can be specified on the
- // command line. This is intended to be used by Java and similar languages
- // to specify which specific class from the proto file is to be generated,
- // though it could have other uses as well. It is empty if no parameter was
- // given.
+ // A parameter to be passed to the generator can be specified on the command
+ // line. This is intended to be used to pass generator specific parameters.
+ // It is empty if no parameter was given. ParseGeneratorParameter (below),
+ // can be used to accept multiple parameters within the single parameter
+ // command line flag.
//
// Returns true if successful. Otherwise, sets *error to a description of
// the problem (e.g. "invalid parameter") and returns false.
@@ -79,18 +79,11 @@ class LIBPROTOC_EXPORT CodeGenerator {
GeneratorContext* generator_context,
string* error) const = 0;
- // Generates code for all given proto files, generating one or more files in
- // the given output directory.
- //
- // This method should be called instead of |Generate()| when
- // |HasGenerateAll()| returns |true|. It is used to emulate legacy semantics
- // when more than one `.proto` file is specified on one compiler invocation.
+ // Generates code for all given proto files.
//
- // WARNING: Please do not use unless legacy semantics force the code generator
- // to produce a single output file for all input files, or otherwise require
- // an examination of all input files first. The canonical code generator
- // design produces one output file per input .proto file, and we do not wish
- // to encourage alternate designs.
+ // WARNING: The canonical code generator design produces one or two output
+ // files per input .proto file, and we do not wish to encourage alternate
+ // designs.
//
// A parameter is given as passed on the command line, as in |Generate()|
// above.
@@ -100,15 +93,13 @@ class LIBPROTOC_EXPORT CodeGenerator {
virtual bool GenerateAll(const vector<const FileDescriptor*>& files,
const string& parameter,
GeneratorContext* generator_context,
- string* error) const {
- *error = "Unimplemented GenerateAll() method.";
- return false;
- }
-
- // Returns true if the code generator expects to receive all FileDescriptors
- // at once (via |GenerateAll()|), rather than one at a time (via
- // |Generate()|). This is required to implement legacy semantics.
- virtual bool HasGenerateAll() const { return false; }
+ string* error) const;
+
+ // This is no longer used, but this class is part of the opensource protobuf
+ // library, so it has to remain to keep vtables the same for the current
+ // version of the library. When protobufs does a api breaking change, the
+ // method can be removed.
+ virtual bool HasGenerateAll() const { return true; }
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodeGenerator);
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc
index bb781b0a..8ab69d02 100644
--- a/src/google/protobuf/compiler/command_line_interface.cc
+++ b/src/google/protobuf/compiler/command_line_interface.cc
@@ -262,6 +262,12 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
return;
}
}
+
+string PluginName(const string& plugin_prefix, const string& directive) {
+ // Assuming the directive starts with "--" and ends with "_out" or "_opt",
+ // strip the "--" and "_out/_opt" and add the plugin prefix.
+ return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6);
+}
} // namespace
// A MultiFileErrorCollector that prints errors to stderr.
@@ -704,6 +710,7 @@ CommandLineInterface::CommandLineInterface()
: mode_(MODE_COMPILE),
print_mode_(PRINT_NONE),
error_format_(ERROR_FORMAT_GCC),
+ direct_dependencies_explicitly_set_(false),
imports_in_descriptor_set_(false),
source_info_in_descriptor_set_(false),
disallow_services_(false),
@@ -784,6 +791,24 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
"--disallow_services was used." << endl;
return 1;
}
+
+ // Enforce --direct_dependencies
+ if (direct_dependencies_explicitly_set_) {
+ bool indirect_imports = false;
+ for (int i = 0; i < parsed_file->dependency_count(); i++) {
+ if (direct_dependencies_.find(parsed_file->dependency(i)->name()) ==
+ direct_dependencies_.end()) {
+ indirect_imports = true;
+ cerr << parsed_file->name()
+ << ": File is imported but not declared in "
+ << "--direct_dependencies: "
+ << parsed_file->dependency(i)->name() << std::endl;
+ }
+ }
+ if (indirect_imports) {
+ return 1;
+ }
+ }
}
// We construct a separate GeneratorContext for each output location. Note
@@ -897,6 +922,7 @@ void CommandLineInterface::Clear() {
executable_name_.clear();
proto_path_.clear();
input_files_.clear();
+ direct_dependencies_.clear();
output_directives_.clear();
codec_type_.clear();
descriptor_set_name_.clear();
@@ -907,6 +933,7 @@ void CommandLineInterface::Clear() {
imports_in_descriptor_set_ = false;
source_info_in_descriptor_set_ = false;
disallow_services_ = false;
+ direct_dependencies_explicitly_set_ = false;
}
bool CommandLineInterface::MakeInputsBeProtoPathRelative(
@@ -986,6 +1013,18 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
return status;
}
+ // Make sure each plugin option has a matching plugin output.
+ for (map<string, string>::const_iterator i = plugin_parameters_.begin();
+ i != plugin_parameters_.end(); ++i) {
+ if (plugins_.find(i->first) == plugins_.end()) {
+ std::cerr << "Unknown flag: "
+ // strip prefix + "gen-" and add back "_opt"
+ << "--" + i->first.substr(plugin_prefix_.size() + 4) + "_opt"
+ << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+ }
+
// If no --proto_path was given, use the current working directory.
if (proto_path_.empty()) {
// Don't use make_pair as the old/default standard library on Solaris
@@ -1154,6 +1193,19 @@ CommandLineInterface::InterpretArgument(const string& name,
proto_path_.push_back(pair<string, string>(virtual_path, disk_path));
}
+ } else if (name == "--direct_dependencies") {
+ if (direct_dependencies_explicitly_set_) {
+ std::cerr << name << " may only be passed once. To specify multiple "
+ "direct dependencies, pass them all as a single "
+ "parameter separated by ':'." << std::endl;
+ return PARSE_ARGUMENT_FAIL;
+ }
+
+ direct_dependencies_explicitly_set_ = true;
+ vector<string> direct = Split(value, ":", true);
+ GOOGLE_DCHECK(direct_dependencies_.empty());
+ direct_dependencies_.insert(direct.begin(), direct.end());
+
} else if (name == "-o" || name == "--descriptor_set_out") {
if (!descriptor_set_name_.empty()) {
std::cerr << name << " may only be passed once." << std::endl;
@@ -1301,15 +1353,22 @@ CommandLineInterface::InterpretArgument(const string& name,
(plugin_prefix_.empty() || !HasSuffixString(name, "_out"))) {
// Check if it's a generator option flag.
generator_info = FindOrNull(generators_by_option_name_, name);
- if (generator_info == NULL) {
- std::cerr << "Unknown flag: " << name << std::endl;
- return PARSE_ARGUMENT_FAIL;
- } else {
+ if (generator_info != NULL) {
string* parameters = &generator_parameters_[generator_info->flag_name];
if (!parameters->empty()) {
parameters->append(",");
}
parameters->append(value);
+ } else if (HasPrefixString(name, "--") && HasSuffixString(name, "_opt")) {
+ string* parameters =
+ &plugin_parameters_[PluginName(plugin_prefix_, name)];
+ if (!parameters->empty()) {
+ parameters->append(",");
+ }
+ parameters->append(value);
+ } else {
+ std::cerr << "Unknown flag: " << name << std::endl;
+ return PARSE_ARGUMENT_FAIL;
}
} else {
// It's an output flag. Add it to the output directives.
@@ -1428,12 +1487,16 @@ bool CommandLineInterface::GenerateOutput(
HasSuffixString(output_directive.name, "_out"))
<< "Bad name for plugin generator: " << output_directive.name;
- // Strip the "--" and "_out" and add the plugin prefix.
- string plugin_name = plugin_prefix_ + "gen-" +
- output_directive.name.substr(2, output_directive.name.size() - 6);
-
+ string plugin_name = PluginName(plugin_prefix_ , output_directive.name);
+ string parameters = output_directive.parameter;
+ if (!plugin_parameters_[plugin_name].empty()) {
+ if (!parameters.empty()) {
+ parameters.append(",");
+ }
+ parameters.append(plugin_parameters_[plugin_name]);
+ }
if (!GeneratePluginOutput(parsed_files, plugin_name,
- output_directive.parameter,
+ parameters,
generator_context, &error)) {
std::cerr << output_directive.name << ": " << error << std::endl;
return false;
@@ -1447,24 +1510,11 @@ bool CommandLineInterface::GenerateOutput(
}
parameters.append(generator_parameters_[output_directive.name]);
}
- if (output_directive.generator->HasGenerateAll()) {
- if (!output_directive.generator->GenerateAll(
- parsed_files, parameters, generator_context, &error)) {
- // Generator returned an error.
- std::cerr << output_directive.name << ": "
- << ": " << error << std::endl;
- return false;
- }
- } else {
- for (int i = 0; i < parsed_files.size(); i++) {
- if (!output_directive.generator->Generate(parsed_files[i], parameters,
- generator_context, &error)) {
- // Generator returned an error.
- std::cerr << output_directive.name << ": " << parsed_files[i]->name()
- << ": " << error << std::endl;
- return false;
- }
- }
+ if (!output_directive.generator->GenerateAll(
+ parsed_files, parameters, generator_context, &error)) {
+ // Generator returned an error.
+ std::cerr << output_directive.name << ": " << error << std::endl;
+ return false;
}
}
diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h
index d1377666..d779fc87 100644
--- a/src/google/protobuf/compiler/command_line_interface.h
+++ b/src/google/protobuf/compiler/command_line_interface.h
@@ -55,6 +55,11 @@ class FileDescriptor; // descriptor.h
class FileDescriptorProto; // descriptor.pb.h
template<typename T> class RepeatedPtrField; // repeated_field.h
+} // namespace protobuf
+} // namespace google
+
+namespace google {
+namespace protobuf {
namespace compiler {
class CodeGenerator; // code_generator.h
@@ -141,14 +146,14 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// plugin [--out=OUTDIR] [--parameter=PARAMETER] PROTO_FILES < DESCRIPTORS
// --out indicates the output directory (as passed to the --foo_out
// parameter); if omitted, the current directory should be used. --parameter
- // gives the generator parameter, if any was provided. The PROTO_FILES list
- // the .proto files which were given on the compiler command-line; these are
- // the files for which the plugin is expected to generate output code.
- // Finally, DESCRIPTORS is an encoded FileDescriptorSet (as defined in
- // descriptor.proto). This is piped to the plugin's stdin. The set will
- // include descriptors for all the files listed in PROTO_FILES as well as
- // all files that they import. The plugin MUST NOT attempt to read the
- // PROTO_FILES directly -- it must use the FileDescriptorSet.
+ // gives the generator parameter, if any was provided (see below). The
+ // PROTO_FILES list the .proto files which were given on the compiler
+ // command-line; these are the files for which the plugin is expected to
+ // generate output code. Finally, DESCRIPTORS is an encoded FileDescriptorSet
+ // (as defined in descriptor.proto). This is piped to the plugin's stdin.
+ // The set will include descriptors for all the files listed in PROTO_FILES as
+ // well as all files that they import. The plugin MUST NOT attempt to read
+ // the PROTO_FILES directly -- it must use the FileDescriptorSet.
//
// The plugin should generate whatever files are necessary, as code generators
// normally do. It should write the names of all files it generates to
@@ -156,6 +161,13 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// names or relative to the current directory. If any errors occur, error
// messages should be written to stderr. If an error is fatal, the plugin
// should exit with a non-zero exit code.
+ //
+ // Plugins can have generator parameters similar to normal built-in
+ // generators. Extra generator parameters can be passed in via a matching
+ // "_opt" parameter. For example:
+ // protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz
+ // This will pass "enable_bar,enable_baz" as the parameter to the plugin.
+ //
void AllowPlugins(const string& exe_name_prefix);
// Run the Protocol Compiler with the given command-line parameters.
@@ -311,6 +323,8 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// protoc --foo_out=outputdir --foo_opt=enable_bar ...
// Then there will be an entry ("--foo_out", "enable_bar") in this map.
map<string, string> generator_parameters_;
+ // Similar to generator_parameters_, but stores the parameters for plugins.
+ map<string, string> plugin_parameters_;
// See AllowPlugins(). If this is empty, plugins aren't allowed.
string plugin_prefix_;
@@ -347,6 +361,11 @@ class LIBPROTOC_EXPORT CommandLineInterface {
vector<pair<string, string> > proto_path_; // Search path for proto files.
vector<string> input_files_; // Names of the input proto files.
+ // Names of proto files which are allowed to be imported. Used by build
+ // systems to enforce depend-on-what-you-import.
+ set<string> direct_dependencies_;
+ bool direct_dependencies_explicitly_set_;
+
// output_directives_ lists all the files we are supposed to output and what
// generator to use for each.
struct OutputDirective {
diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc
index 0ebf9b6a..dfbaa45a 100644
--- a/src/google/protobuf/compiler/command_line_interface_unittest.cc
+++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc
@@ -653,6 +653,44 @@ TEST_F(CommandLineInterfaceTest, ExtraGeneratorParameters) {
"test_generator", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b");
}
+TEST_F(CommandLineInterfaceTest, ExtraPluginParameters) {
+ // Test that generator parameters specified with the option flag are
+ // correctly passed to the code generator.
+
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "message Foo {}\n");
+ // Create the "a" and "b" sub-directories.
+ CreateTempDir("a");
+ CreateTempDir("b");
+
+ Run("protocol_compiler "
+ "--plug_opt=foo1 "
+ "--plug_out=bar:$tmpdir/a "
+ "--plug_opt=foo2 "
+ "--plug_out=baz:$tmpdir/b "
+ "--plug_opt=foo3 "
+ "--proto_path=$tmpdir foo.proto");
+
+ ExpectNoErrors();
+ ExpectGenerated(
+ "test_plugin", "bar,foo1,foo2,foo3", "foo.proto", "Foo", "a");
+ ExpectGenerated(
+ "test_plugin", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b");
+}
+
+TEST_F(CommandLineInterfaceTest, UnrecognizedExtraParameters) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "message Foo {}\n");
+
+ Run("protocol_compiler --plug_out=TestParameter:$tmpdir "
+ "--unknown_plug_opt=Foo "
+ "--proto_path=$tmpdir foo.proto");
+
+ ExpectErrorSubstring("Unknown flag: --unknown_plug_opt");
+}
+
TEST_F(CommandLineInterfaceTest, Insert) {
// Test running a generator that inserts code into another's output.
@@ -719,6 +757,11 @@ TEST_F(CommandLineInterfaceTest, TrailingBackslash) {
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
}
+TEST_F(CommandLineInterfaceTest, Win32ErrorMessage) {
+ EXPECT_EQ("The system cannot find the file specified.\r\n",
+ Subprocess::Win32ErrorMessage(ERROR_FILE_NOT_FOUND));
+}
+
#endif // defined(_WIN32) || defined(__CYGWIN__)
TEST_F(CommandLineInterfaceTest, PathLookup) {
@@ -866,6 +909,92 @@ TEST_F(CommandLineInterfaceTest, AllowServicesHasService) {
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
}
+TEST_F(CommandLineInterfaceTest, DirectDependencies_Missing_EmptyList) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"bar.proto\";\n"
+ "message Foo { optional Bar bar = 1; }");
+ CreateTempFile("bar.proto",
+ "syntax = \"proto2\";\n"
+ "message Bar { optional string text = 1; }");
+
+ Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir "
+ "--direct_dependencies= foo.proto");
+
+ ExpectErrorText(
+ "foo.proto: File is imported but not declared in --direct_dependencies: "
+ "bar.proto\n");
+}
+
+TEST_F(CommandLineInterfaceTest, DirectDependencies_Missing) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"bar.proto\";\n"
+ "import \"bla.proto\";\n"
+ "message Foo { optional Bar bar = 1; optional Bla bla = 2; }");
+ CreateTempFile("bar.proto",
+ "syntax = \"proto2\";\n"
+ "message Bar { optional string text = 1; }");
+ CreateTempFile("bla.proto",
+ "syntax = \"proto2\";\n"
+ "message Bla { optional int64 number = 1; }");
+
+ Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir "
+ "--direct_dependencies=bla.proto foo.proto");
+
+ ExpectErrorText(
+ "foo.proto: File is imported but not declared in --direct_dependencies: "
+ "bar.proto\n");
+}
+
+TEST_F(CommandLineInterfaceTest, DirectDependencies_NoViolation) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"bar.proto\";\n"
+ "message Foo { optional Bar bar = 1; }");
+ CreateTempFile("bar.proto",
+ "syntax = \"proto2\";\n"
+ "message Bar { optional string text = 1; }");
+
+ Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir "
+ "--direct_dependencies=bar.proto foo.proto");
+
+ ExpectNoErrors();
+}
+
+TEST_F(CommandLineInterfaceTest, DirectDependencies_NoViolation_MultiImports) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n"
+ "import \"bar.proto\";\n"
+ "import \"bla.proto\";\n"
+ "message Foo { optional Bar bar = 1; optional Bla bla = 2; }");
+ CreateTempFile("bar.proto",
+ "syntax = \"proto2\";\n"
+ "message Bar { optional string text = 1; }");
+ CreateTempFile("bla.proto",
+ "syntax = \"proto2\";\n"
+ "message Bla { optional int64 number = 1; }");
+
+ Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir "
+ "--direct_dependencies=bar.proto:bla.proto foo.proto");
+
+ ExpectNoErrors();
+}
+
+TEST_F(CommandLineInterfaceTest, DirectDependencies_ProvidedMultipleTimes) {
+ CreateTempFile("foo.proto",
+ "syntax = \"proto2\";\n");
+
+ Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir "
+ "--direct_dependencies=bar.proto --direct_dependencies=bla.proto "
+ "foo.proto");
+
+ ExpectErrorText(
+ "--direct_dependencies may only be passed once. To specify multiple "
+ "direct dependencies, pass them all as a single parameter separated by "
+ "':'.\n");
+}
+
TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) {
// Test that we can accept working-directory-relative input files.
diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
index 77451ab1..deef290b 100644
--- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc
@@ -99,7 +99,6 @@ class MockGeneratorContext : public GeneratorContext {
&actual_contents, true));
EXPECT_TRUE(actual_contents == *expected_contents)
<< physical_filename << " needs to be regenerated. Please run "
- "google/protobuf/compiler/release_compiler.sh and "
"generate_descriptor_proto.sh. Then add this file "
"to your CL.";
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/cpp_enum.cc
index 62b7ed4e..6ced26bc 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum.cc
@@ -260,7 +260,7 @@ void EnumGenerator::GenerateMethods(io::Printer* printer) {
printer->Print(vars,
"bool $classname$_IsValid(int value) {\n"
- " switch(value) {\n");
+ " switch (value) {\n");
// Multiple values may have the same number. Make sure we only cover
// each number once by first constructing a set containing all valid
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
index ffd81529..c3dfa817 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.cc
@@ -83,13 +83,13 @@ void EnumFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ $type$ $classname$::$name$() const {\n"
+ "$inline$$type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_);\n"
"}\n"
- "$inline$ void $classname$::set_$name$($type$ value) {\n");
+ "$inline$void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
" assert($type$_IsValid(value));\n");
@@ -187,16 +187,16 @@ void EnumOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ $type$ $classname$::$name$() const {\n"
+ "$inline$$type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return static_cast< $type$ >($oneof_prefix$$name$_);\n"
" }\n"
" return static_cast< $type$ >($default$);\n"
"}\n"
- "$inline$ void $classname$::set_$name$($type$ value) {\n");
+ "$inline$void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
" assert($type$_IsValid(value));\n");
@@ -263,13 +263,13 @@ void RepeatedEnumFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ $type$ $classname$::$name$(int index) const {\n"
+ "$inline$$type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_.Get(index));\n"
"}\n"
- "$inline$ void $classname$::set_$name$(int index, $type$ value) {\n");
+ "$inline$void $classname$::set_$name$(int index, $type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
" assert($type$_IsValid(value));\n");
@@ -278,7 +278,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::add_$name$($type$ value) {\n");
+ "$inline$void $classname$::add_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
" assert($type$_IsValid(value));\n");
@@ -288,12 +288,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n");
printer->Print(variables,
- "$inline$ const ::google::protobuf::RepeatedField<int>&\n"
+ "$inline$const ::google::protobuf::RepeatedField<int>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$ ::google::protobuf::RepeatedField<int>*\n"
+ "$inline$::google::protobuf::RepeatedField<int>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -311,6 +311,11 @@ GenerateMergingCode(io::Printer* printer) const {
}
void RepeatedEnumFieldGenerator::
+GenerateUnsafeMergingCode(io::Printer* printer) const {
+ printer->Print(variables_, "$name$_.UnsafeMergeFrom(from.$name$_);\n");
+}
+
+void RepeatedEnumFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
}
@@ -475,10 +480,11 @@ void RepeatedEnumFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
- " int data_size = 0;\n");
+ " size_t data_size = 0;\n"
+ " unsigned int count = this->$name$_size();");
printer->Indent();
printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n"
+ "for (unsigned int i = 0; i < count; i++) {\n"
" data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n"
" this->$name$(i));\n"
"}\n");
@@ -489,13 +495,14 @@ GenerateByteSize(io::Printer* printer) const {
" total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
"}\n"
+ "int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- "_$name$_cached_byte_size_ = data_size;\n"
+ "_$name$_cached_byte_size_ = cached_size;\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
"total_size += data_size;\n");
} else {
printer->Print(variables_,
- "total_size += $tag_size$ * this->$name$_size() + data_size;\n");
+ "total_size += ($tag_size$UL * count) + data_size;\n");
}
printer->Outdent();
printer->Print("}\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.h b/src/google/protobuf/compiler/cpp/cpp_enum_field.h
index fe21c575..57ffeec5 100644
--- a/src/google/protobuf/compiler/cpp/cpp_enum_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_enum_field.h
@@ -101,6 +101,7 @@ class RepeatedEnumFieldGenerator : public FieldGenerator {
bool is_inline) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
+ void GenerateUnsafeMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/cpp_extension.cc
index c42f1627..4554c72c 100644
--- a/src/google/protobuf/compiler/cpp/cpp_extension.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_extension.cc
@@ -178,28 +178,30 @@ void ExtensionGenerator::GenerateRegistration(io::Printer* printer) {
switch (descriptor_->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
- printer->Print(vars,
- "::google::protobuf::internal::ExtensionSet::RegisterEnumExtension(\n"
- " &$extendee$::default_instance(),\n"
- " $number$, $field_type$, $is_repeated$, $is_packed$,\n");
+ printer->Print(
+ vars,
+ "::google::protobuf::internal::ExtensionSet::RegisterEnumExtension(\n"
+ " $extendee$::internal_default_instance(),\n"
+ " $number$, $field_type$, $is_repeated$, $is_packed$,\n");
printer->Print(
" &$type$_IsValid);\n",
"type", ClassName(descriptor_->enum_type(), true));
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
- printer->Print(vars,
- "::google::protobuf::internal::ExtensionSet::RegisterMessageExtension(\n"
- " &$extendee$::default_instance(),\n"
- " $number$, $field_type$, $is_repeated$, $is_packed$,\n");
printer->Print(
- " &$type$::default_instance());\n",
- "type", ClassName(descriptor_->message_type(), true));
+ vars,
+ "::google::protobuf::internal::ExtensionSet::RegisterMessageExtension(\n"
+ " $extendee$::internal_default_instance(),\n"
+ " $number$, $field_type$, $is_repeated$, $is_packed$,\n");
+ printer->Print(" $type$::internal_default_instance());\n", "type",
+ ClassName(descriptor_->message_type(), true));
break;
default:
- printer->Print(vars,
- "::google::protobuf::internal::ExtensionSet::RegisterExtension(\n"
- " &$extendee$::default_instance(),\n"
- " $number$, $field_type$, $is_repeated$, $is_packed$);\n");
+ printer->Print(
+ vars,
+ "::google::protobuf::internal::ExtensionSet::RegisterExtension(\n"
+ " $extendee$::internal_default_instance(),\n"
+ " $number$, $field_type$, $is_repeated$, $is_packed$);\n");
break;
}
}
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/cpp_field.h
index 3b012527..fdd338a6 100644
--- a/src/google/protobuf/compiler/cpp/cpp_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_field.h
@@ -136,6 +136,13 @@ class FieldGenerator {
// GenerateMergeFrom method.
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
+ // The same, but the generated code may or may not check the possibility that
+ // the two objects being merged have the same address. To be safe, callers
+ // should avoid calling this unless they know the objects are different.
+ virtual void GenerateUnsafeMergingCode(io::Printer* printer) const {
+ GenerateMergingCode(printer);
+ }
+
// Generate lines of code (statements, not declarations) which swaps
// this field and the corresponding field of another message, which
// is stored in the generated code variable "other". This is used to
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/cpp_file.cc
index b3eca660..369497ce 100644
--- a/src/google/protobuf/compiler/cpp/cpp_file.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_file.cc
@@ -89,7 +89,7 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
new ExtensionGenerator(file->extension(i), options));
}
- SplitStringUsing(file_->package(), ".", &package_parts_);
+ package_parts_ = Split(file_->package(), ".", true);
}
FileGenerator::~FileGenerator() {}
@@ -336,6 +336,20 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
// Generate classes.
for (int i = 0; i < file_->message_type_count(); i++) {
+ if (i == 0 && HasGeneratedMethods(file_, options_)) {
+ printer->Print(
+ "\n"
+ "namespace {\n"
+ "\n"
+ "static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD"
+ " GOOGLE_ATTRIBUTE_NORETURN;\n"
+ "static void MergeFromFail(int line) {\n"
+ " ::google::protobuf::internal::MergeFromFail(__FILE__, line);\n"
+ "}\n"
+ "\n"
+ "} // namespace\n"
+ "\n");
+ }
printer->Print("\n");
printer->Print(kThickSeparator);
printer->Print("\n");
@@ -449,6 +463,7 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
// In optimize_for = LITE_RUNTIME mode, we don't generate AssignDescriptors()
// and we only use AddDescriptors() to allocate default instances.
+
if (HasDescriptorMethods(file_, options_)) {
printer->Print(
"\n"
@@ -500,15 +515,15 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
// AssignDescriptors(). All later times, waits for the first call to
// complete and then returns.
printer->Print(
- "namespace {\n"
- "\n"
- "GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);\n"
- "inline void protobuf_AssignDescriptorsOnce() {\n"
- " ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,\n"
- " &$assigndescriptorsname$);\n"
- "}\n"
- "\n",
- "assigndescriptorsname", GlobalAssignDescriptorsName(file_->name()));
+ "namespace {\n"
+ "\n"
+ "GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);\n"
+ "void protobuf_AssignDescriptorsOnce() {\n"
+ " ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,\n"
+ " &$assigndescriptorsname$);\n"
+ "}\n"
+ "\n",
+ "assigndescriptorsname", GlobalAssignDescriptorsName(file_->name()));
// protobuf_RegisterTypes(): Calls
// MessageFactory::InternalRegisterGeneratedType() for each message type.
@@ -548,44 +563,68 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
// -----------------------------------------------------------------
- // Now generate the AddDescriptors() function.
- PrintHandlingOptionalStaticInitializers(
- file_, options_, printer,
- // With static initializers.
- // Note that we don't need any special synchronization in the following
- // code
- // because it is called at static init time before any threads exist.
- "void $adddescriptorsname$() GOOGLE_ATTRIBUTE_COLD;\n"
- "void $adddescriptorsname$() {\n"
- " static bool already_here = false;\n"
- " if (already_here) return;\n"
- " already_here = true;\n"
- " GOOGLE_PROTOBUF_VERIFY_VERSION;\n"
- "\n",
- // Without.
- "void $adddescriptorsname$_impl() {\n"
+ // Now generate the InitDefaults() function.
+ printer->Print(
+ "void $initdefaultsname$_impl() {\n"
" GOOGLE_PROTOBUF_VERIFY_VERSION;\n"
"\n",
// Vars.
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()));
+ "initdefaultsname", GlobalInitDefaultsName(file_->name()));
printer->Indent();
- // Call the AddDescriptors() methods for all of our dependencies, to make
+ // Call the InitDefaults() methods for all of our dependencies, to make
// sure they get added first.
for (int i = 0; i < file_->dependency_count(); i++) {
const FileDescriptor* dependency = file_->dependency(i);
// Print the namespace prefix for the dependency.
string add_desc_name = QualifiedFileLevelSymbol(
- dependency->package(), GlobalAddDescriptorsName(dependency->name()));
+ dependency->package(), GlobalInitDefaultsName(dependency->name()));
// Call its AddDescriptors function.
printer->Print(
"$name$();\n",
"name", add_desc_name);
}
+ // Allocate and initialize default instances. This can't be done lazily
+ // since default instances are returned by simple accessors and are used with
+ // extensions. Speaking of which, we also register extensions at this time.
+ for (int i = 0; i < file_->message_type_count(); i++) {
+ message_generators_[i]->GenerateDefaultInstanceAllocator(printer);
+ }
+ for (int i = 0; i < file_->extension_count(); i++) {
+ extension_generators_[i]->GenerateRegistration(printer);
+ }
+ for (int i = 0; i < file_->message_type_count(); i++) {
+ message_generators_[i]->GenerateDefaultInstanceInitializer(printer);
+ }
+ printer->Outdent();
+ printer->Print(
+ "}\n"
+ "\n"
+ "GOOGLE_PROTOBUF_DECLARE_ONCE($initdefaultsname$_once_);\n"
+ "void $initdefaultsname$() {\n"
+ " ::google::protobuf::GoogleOnceInit(&$initdefaultsname$_once_,\n"
+ " &$initdefaultsname$_impl);\n"
+ "}\n",
+ "initdefaultsname", GlobalInitDefaultsName(file_->name()));
+
+ // -----------------------------------------------------------------
+
+ // Now generate the AddDescriptors() function.
+ printer->Print(
+ "void $adddescriptorsname$_impl() {\n"
+ " GOOGLE_PROTOBUF_VERIFY_VERSION;\n"
+ "\n"
+ " $initdefaultsname$();\n",
+ // Vars.
+ "adddescriptorsname", GlobalAddDescriptorsName(file_->name()),
+ "initdefaultsname", GlobalInitDefaultsName(file_->name()));
+
+ printer->Indent();
if (HasDescriptorMethods(file_, options_)) {
- // Embed the descriptor. We simply serialize the entire FileDescriptorProto
+ // Embed the descriptor. We simply serialize the entire
+ // FileDescriptorProto
// and embed it as a string literal, which is parsed and built into real
// descriptors at initialization time.
FileDescriptorProto file_proto;
@@ -655,30 +694,37 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
"filename", file_->name());
}
- // Allocate and initialize default instances. This can't be done lazily
- // since default instances are returned by simple accessors and are used with
- // extensions. Speaking of which, we also register extensions at this time.
- for (int i = 0; i < file_->message_type_count(); i++) {
- message_generators_[i]->GenerateDefaultInstanceAllocator(printer);
- }
- for (int i = 0; i < file_->extension_count(); i++) {
- extension_generators_[i]->GenerateRegistration(printer);
- }
- for (int i = 0; i < file_->message_type_count(); i++) {
- message_generators_[i]->GenerateDefaultInstanceInitializer(printer);
+ // Call the AddDescriptors() methods for all of our dependencies, to make
+ // sure they get added first.
+ for (int i = 0; i < file_->dependency_count(); i++) {
+ const FileDescriptor* dependency = file_->dependency(i);
+ // Print the namespace prefix for the dependency.
+ string add_desc_name = QualifiedFileLevelSymbol(
+ dependency->package(), GlobalAddDescriptorsName(dependency->name()));
+ // Call its AddDescriptors function.
+ printer->Print("$adddescriptorsname$();\n", "adddescriptorsname",
+ add_desc_name);
}
printer->Print(
- "::google::protobuf::internal::OnShutdown(&$shutdownfilename$);\n",
- "shutdownfilename", GlobalShutdownFileName(file_->name()));
+ "::google::protobuf::internal::OnShutdown(&$shutdownfilename$);\n",
+ "shutdownfilename", GlobalShutdownFileName(file_->name()));
printer->Outdent();
printer->Print(
- "}\n"
- "\n");
+ "}\n"
+ "\n"
+ "GOOGLE_PROTOBUF_DECLARE_ONCE($adddescriptorsname$_once_);\n"
+ "void $adddescriptorsname$() {\n"
+ " ::google::protobuf::GoogleOnceInit(&$adddescriptorsname$_once_,\n"
+ " &$adddescriptorsname$_impl);\n"
+ "}\n",
+ "adddescriptorsname", GlobalAddDescriptorsName(file_->name()));
- PrintHandlingOptionalStaticInitializers(
- file_, options_, printer,
+ if (!StaticInitializersForced(file_, options_)) {
+ printer->Print("#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n");
+ }
+ printer->Print(
// With static initializers.
"// Force AddDescriptors() to be called at static initialization time.\n"
"struct StaticDescriptorInitializer_$filename$ {\n"
@@ -686,15 +732,12 @@ void FileGenerator::GenerateBuildDescriptors(io::Printer* printer) {
" $adddescriptorsname$();\n"
" }\n"
"} static_descriptor_initializer_$filename$_;\n",
- // Without.
- "GOOGLE_PROTOBUF_DECLARE_ONCE($adddescriptorsname$_once_);\n"
- "void $adddescriptorsname$() {\n"
- " ::google::protobuf::GoogleOnceInit(&$adddescriptorsname$_once_,\n"
- " &$adddescriptorsname$_impl);\n"
- "}\n",
// Vars.
"adddescriptorsname", GlobalAddDescriptorsName(file_->name()), "filename",
FilenameIdentifier(file_->name()));
+ if (!StaticInitializersForced(file_, options_)) {
+ printer->Print("#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n");
+ }
}
void FileGenerator::GenerateNamespaceOpeners(io::Printer* printer) {
@@ -892,12 +935,14 @@ void FileGenerator::GenerateGlobalStateFunctionDeclarations(
// Forward-declare the AddDescriptors, AssignDescriptors, and ShutdownFile
// functions, so that we can declare them to be friends of each class.
printer->Print(
- "\n"
- "// Internal implementation detail -- do not call these.\n"
- "void $dllexport_decl$$adddescriptorsname$();\n",
- "adddescriptorsname", GlobalAddDescriptorsName(file_->name()),
- "dllexport_decl",
- options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
+ "\n"
+ "// Internal implementation detail -- do not call these.\n"
+ "void $dllexport_decl$$adddescriptorsname$();\n"
+ "void $dllexport_decl$$initdefaultsname$();\n",
+ "initdefaultsname", GlobalInitDefaultsName(file_->name()),
+ "adddescriptorsname", GlobalAddDescriptorsName(file_->name()),
+ "dllexport_decl",
+ options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
printer->Print(
// Note that we don't put dllexport_decl on these because they are only
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
index 2ad4d36a..6d844cc2 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.cc
@@ -415,7 +415,8 @@ string DefaultValue(const FieldDescriptor* field) {
CEscape(field->default_value_string())) +
"\"";
case FieldDescriptor::CPPTYPE_MESSAGE:
- return FieldMessageTypeName(field) + "::default_instance()";
+ return "*" + FieldMessageTypeName(field) +
+ "::internal_default_instance()";
}
// Can't actually get here; make compiler happy. (We could add a default
// case above but then we wouldn't get the nice compiler warning when a
@@ -444,6 +445,10 @@ string GlobalAddDescriptorsName(const string& filename) {
return "protobuf_AddDesc_" + FilenameIdentifier(filename);
}
+string GlobalInitDefaultsName(const string& filename) {
+ return "protobuf_InitDefaults_" + FilenameIdentifier(filename);
+}
+
// Return the name of the AssignDescriptors() function for a given file.
string GlobalAssignDescriptorsName(const string& filename) {
return "protobuf_AssignDesc_" + FilenameIdentifier(filename);
@@ -500,40 +505,6 @@ bool StaticInitializersForced(const FileDescriptor* file,
return false;
}
-void PrintHandlingOptionalStaticInitializers(
- const FileDescriptor* file, const Options& options, io::Printer* printer,
- const char* with_static_init, const char* without_static_init,
- const char* var1, const string& val1, const char* var2,
- const string& val2) {
- map<string, string> vars;
- if (var1) {
- vars[var1] = val1;
- }
- if (var2) {
- vars[var2] = val2;
- }
- PrintHandlingOptionalStaticInitializers(
- vars, file, options, printer, with_static_init, without_static_init);
-}
-
-void PrintHandlingOptionalStaticInitializers(const map<string, string>& vars,
- const FileDescriptor* file,
- const Options& options,
- io::Printer* printer,
- const char* with_static_init,
- const char* without_static_init) {
- if (StaticInitializersForced(file, options)) {
- printer->Print(vars, with_static_init);
- } else {
- printer->Print(vars, (string(
- "#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n") +
- without_static_init +
- "#else\n" +
- with_static_init +
- "#endif\n").c_str());
- }
-}
-
static bool HasMapFields(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); ++i) {
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/cpp_helpers.h
index 018acfca..3a0c0388 100644
--- a/src/google/protobuf/compiler/cpp/cpp_helpers.h
+++ b/src/google/protobuf/compiler/cpp/cpp_helpers.h
@@ -147,6 +147,9 @@ string FilenameIdentifier(const string& filename);
// Return the name of the AddDescriptors() function for a given file.
string GlobalAddDescriptorsName(const string& filename);
+// Return the name of the InitDefaults() function for a given file.
+string GlobalInitDefaultsName(const string& filename);
+
// Return the name of the AssignDescriptors() function for a given file.
string GlobalAssignDescriptorsName(const string& filename);
@@ -223,22 +226,6 @@ inline bool HasFastArraySerialization(const FileDescriptor* file,
bool StaticInitializersForced(const FileDescriptor* file,
const Options& options);
-// Prints 'with_static_init' if static initializers have to be used for the
-// provided file. Otherwise emits both 'with_static_init' and
-// 'without_static_init' using #ifdef.
-void PrintHandlingOptionalStaticInitializers(
- const FileDescriptor* file, const Options& options, io::Printer* printer,
- const char* with_static_init, const char* without_static_init,
- const char* var1 = NULL, const string& val1 = "", const char* var2 = NULL,
- const string& val2 = "");
-
-void PrintHandlingOptionalStaticInitializers(const map<string, string>& vars,
- const FileDescriptor* file,
- const Options& options,
- io::Printer* printer,
- const char* with_static_init,
- const char* without_static_init);
-
inline bool IsMapEntryMessage(const Descriptor* descriptor) {
return descriptor->options().map_entry();
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
index 0588e34e..31ac9ca7 100644
--- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_map_field.cc
@@ -399,7 +399,8 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
void MapFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
- "total_size += $tag_size$ * this->$name$_size();\n"
+ "total_size += $tag_size$ *\n"
+ " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
"{\n"
" ::google::protobuf::scoped_ptr<$map_classname$> entry;\n"
" for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/cpp_message.cc
index 405a5fed..efc56ddc 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message.cc
@@ -85,14 +85,13 @@ struct FieldOrderingByNumber {
// 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()];
+std::vector<const FieldDescriptor*> SortFieldsByNumber(
+ const Descriptor* descriptor) {
+ std::vector<const FieldDescriptor*> fields(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());
+ std::sort(fields.begin(), fields.end(), FieldOrderingByNumber());
return fields;
}
@@ -227,59 +226,150 @@ class FieldGroup {
// used in a vector.
};
+// Helper for the code that emits the Clear() method.
+bool CanInitializeByZeroing(const FieldDescriptor* field) {
+ if (field->is_repeated() || field->is_extension()) return false;
+ switch (field->cpp_type()) {
+ case internal::WireFormatLite::CPPTYPE_ENUM:
+ return field->default_value_enum()->number() == 0;
+ case internal::WireFormatLite::CPPTYPE_INT32:
+ return field->default_value_int32() == 0;
+ case internal::WireFormatLite::CPPTYPE_INT64:
+ return field->default_value_int64() == 0;
+ case internal::WireFormatLite::CPPTYPE_UINT32:
+ return field->default_value_uint32() == 0;
+ case internal::WireFormatLite::CPPTYPE_UINT64:
+ return field->default_value_uint64() == 0;
+ case internal::WireFormatLite::CPPTYPE_FLOAT:
+ return field->default_value_float() == 0;
+ case internal::WireFormatLite::CPPTYPE_DOUBLE:
+ return field->default_value_double() == 0;
+ case internal::WireFormatLite::CPPTYPE_BOOL:
+ return field->default_value_bool() == false;
+ default:
+ return false;
+ }
+}
+
// Reorder 'fields' so that if the fields are output into a c++ class in the new
-// order, the alignment padding is minimized. We try to do this while keeping
-// each field as close as possible to its original position so that we don't
-// reduce cache locality much for function that access each field in order.
+// order, fields of similiar family (see below) are together and within each
+// family, alignment padding is minimized.
+//
+// We try to do this while keeping each field as close as possible to its
+// declaration order (from the .proto file) so that we don't reduce cache
+// locality much for function that access each field in order. This is also the
+// only (weak) signal we have for author intent concerning field layout.
+//
+// TODO(ckennelly): Update these functions to use the optimized layout order
+// for their access patterns.
+//
+// TODO(ckennelly): If/when we have profiles available for the compiler, use
+// those rather than respect declaration order.
+//
+// We classify each field into a particular "family" of fields, that we perform
+// the same operation on in our generated functions.
+//
+// REPEATED is placed first, as the C++ compiler automatically initializes
+// these fields in layout order.
+//
+// STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and
+// calls ArenaStringPtr::Destroy on each.
+//
+// MESSAGE is grouped next, as our Clear/SharedDtor code walks it and calls
+// delete on each. We initialize these fields with a NULL pointer (see
+// MessageFieldGenerator::GenerateConstructorCode).
+// TODO(ckennelly): memset these in SharedCtor.
+//
+// ZERO_INITIALIZABLE is memset in Clear/SharedCtor
+//
+// OTHER these fields are initialized one-by-one.
void OptimizePadding(vector<const FieldDescriptor*>* fields) {
+ // The sorted numeric order of Family determines the declaration order in the
+ // memory layout.
+ enum Family {
+ REPEATED = 0,
+ STRING = 1,
+ MESSAGE = 2,
+ ZERO_INITIALIZABLE = 3,
+ OTHER = 4,
+ kMaxFamily
+ };
+
// First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
- vector<FieldGroup> aligned_to_1, aligned_to_4, aligned_to_8;
+ vector<FieldGroup> aligned_to_1[kMaxFamily];
+ vector<FieldGroup> aligned_to_4[kMaxFamily];
+ vector<FieldGroup> aligned_to_8[kMaxFamily];
for (int i = 0; i < fields->size(); ++i) {
- switch (EstimateAlignmentSize((*fields)[i])) {
- case 1: aligned_to_1.push_back(FieldGroup(i, (*fields)[i])); break;
- case 4: aligned_to_4.push_back(FieldGroup(i, (*fields)[i])); break;
- case 8: aligned_to_8.push_back(FieldGroup(i, (*fields)[i])); break;
- default:
- GOOGLE_LOG(FATAL) << "Unknown alignment size.";
+ const FieldDescriptor* field = (*fields)[i];
+
+ Family f = OTHER;
+ if (field->is_repeated()) {
+ f = REPEATED;
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
+ f = STRING;
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ f = MESSAGE;
+ } else if (CanInitializeByZeroing(field)) {
+ f = ZERO_INITIALIZABLE;
}
- }
- // Now group fields aligned to 1 byte into sets of 4, and treat those like a
- // single field aligned to 4 bytes.
- for (int i = 0; i < aligned_to_1.size(); i += 4) {
- FieldGroup field_group;
- for (int j = i; j < aligned_to_1.size() && j < i + 4; ++j) {
- field_group.Append(aligned_to_1[j]);
+ switch (EstimateAlignmentSize(field)) {
+ case 1: aligned_to_1[f].push_back(FieldGroup(i, field)); break;
+ case 4: aligned_to_4[f].push_back(FieldGroup(i, field)); break;
+ case 8: aligned_to_8[f].push_back(FieldGroup(i, field)); break;
+ default:
+ GOOGLE_LOG(FATAL) << "Unknown alignment size.";
}
- aligned_to_4.push_back(field_group);
}
- // Sort by preferred location to keep fields as close to their original
- // location as possible. Using stable_sort ensures that the output is
- // consistent across runs.
- std::stable_sort(aligned_to_4.begin(), aligned_to_4.end());
- // Now group fields aligned to 4 bytes (or the 4-field groups created above)
- // into pairs, and treat those like a single field aligned to 8 bytes.
- for (int i = 0; i < aligned_to_4.size(); i += 2) {
- FieldGroup field_group;
- for (int j = i; j < aligned_to_4.size() && j < i + 2; ++j) {
- field_group.Append(aligned_to_4[j]);
- }
- if (i == aligned_to_4.size() - 1) {
- // Move incomplete 4-byte block to the end.
- field_group.SetPreferredLocation(fields->size() + 1);
+ // For each family, group fields to optimize padding.
+ for (int f = 0; f < kMaxFamily; f++) {
+ // Now group fields aligned to 1 byte into sets of 4, and treat those like a
+ // single field aligned to 4 bytes.
+ for (int i = 0; i < aligned_to_1[f].size(); i += 4) {
+ FieldGroup field_group;
+ for (int j = i; j < aligned_to_1[f].size() && j < i + 4; ++j) {
+ field_group.Append(aligned_to_1[f][j]);
+ }
+ aligned_to_4[f].push_back(field_group);
+ }
+ // Sort by preferred location to keep fields as close to their declaration
+ // order as possible. Using stable_sort ensures that the output is
+ // consistent across runs.
+ std::stable_sort(aligned_to_4[f].begin(), aligned_to_4[f].end());
+
+ // Now group fields aligned to 4 bytes (or the 4-field groups created above)
+ // into pairs, and treat those like a single field aligned to 8 bytes.
+ for (int i = 0; i < aligned_to_4[f].size(); i += 2) {
+ FieldGroup field_group;
+ for (int j = i; j < aligned_to_4[f].size() && j < i + 2; ++j) {
+ field_group.Append(aligned_to_4[f][j]);
+ }
+ if (i == aligned_to_4[f].size() - 1) {
+ if (f == OTHER) {
+ // Move incomplete 4-byte block to the beginning. This is done to
+ // pair with the (possible) leftover blocks from the
+ // ZERO_INITIALIZABLE family.
+ field_group.SetPreferredLocation(-1);
+ } else {
+ // Move incomplete 4-byte block to the end.
+ field_group.SetPreferredLocation(fields->size() + 1);
+ }
+ }
+ aligned_to_8[f].push_back(field_group);
}
- aligned_to_8.push_back(field_group);
+ // Sort by preferred location.
+ std::stable_sort(aligned_to_8[f].begin(), aligned_to_8[f].end());
}
- // Sort by preferred location.
- std::stable_sort(aligned_to_8.begin(), aligned_to_8.end());
// Now pull out all the FieldDescriptors in order.
fields->clear();
- for (int i = 0; i < aligned_to_8.size(); ++i) {
- fields->insert(fields->end(),
- aligned_to_8[i].fields().begin(),
- aligned_to_8[i].fields().end());
+ for (int f = 0; f < kMaxFamily; ++f) {
+ for (int i = 0; i < aligned_to_8[f].size(); ++i) {
+ fields->insert(fields->end(),
+ aligned_to_8[f][i].fields().begin(),
+ aligned_to_8[f][i].fields().end());
+ }
}
}
@@ -337,6 +427,20 @@ bool HasHasMethod(const FieldDescriptor* field) {
return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE;
}
+size_t HasBitsSize(const Descriptor* descriptor) {
+ // TODO(jieluo) - Optimize _has_bits_ for repeated and oneof fields.
+ size_t sizeof_has_bits = (descriptor->field_count() + 31) / 32 * 4;
+ if (descriptor->field_count() == 0) {
+ // Zero-size arrays aren't technically allowed, and MSVC in particular
+ // doesn't like them. We still need to declare these arrays to make
+ // other code compile. Since this is an uncommon case, we'll just declare
+ // them with size 1 and waste some space. Oh well.
+ sizeof_has_bits = 4;
+ }
+
+ return sizeof_has_bits;
+}
+
// Collects map entry message type information.
void CollectMapInfo(const Descriptor* descriptor,
map<string, string>* variables) {
@@ -389,6 +493,15 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor,
ExtensionGenerator>[descriptor->extension_count()]),
use_dependent_base_(false) {
+ // Compute optimized field order to be used for layout and initialization
+ // purposes.
+ for (int i = 0; i < descriptor_->field_count(); i++) {
+ if (!descriptor_->field(i)->containing_oneof()) {
+ optimized_order_.push_back(descriptor_->field(i));
+ }
+ }
+ OptimizePadding(&optimized_order_);
+
for (int i = 0; i < descriptor->nested_type_count(); i++) {
nested_generators_[i].reset(
new MessageGenerator(descriptor->nested_type(i), options));
@@ -644,11 +757,12 @@ GenerateSingularFieldHasBits(const FieldDescriptor* field,
" return !$name$_.IsCleared();\n"
"}\n");
} else {
- printer->Print(vars,
- "$inline$"
- "bool $classname$::has_$name$() const {\n"
- " return !_is_default_instance_ && $name$_ != NULL;\n"
- "}\n");
+ printer->Print(
+ vars,
+ "$inline$"
+ "bool $classname$::has_$name$() const {\n"
+ " return this != internal_default_instance() && $name$_ != NULL;\n"
+ "}\n");
}
}
}
@@ -805,31 +919,6 @@ GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline) {
}
}
-// Helper for the code that emits the Clear() method.
-static bool CanClearByZeroing(const FieldDescriptor* field) {
- if (field->is_repeated() || field->is_extension()) return false;
- switch (field->cpp_type()) {
- case internal::WireFormatLite::CPPTYPE_ENUM:
- return field->default_value_enum()->number() == 0;
- case internal::WireFormatLite::CPPTYPE_INT32:
- return field->default_value_int32() == 0;
- case internal::WireFormatLite::CPPTYPE_INT64:
- return field->default_value_int64() == 0;
- case internal::WireFormatLite::CPPTYPE_UINT32:
- return field->default_value_uint32() == 0;
- case internal::WireFormatLite::CPPTYPE_UINT64:
- return field->default_value_uint64() == 0;
- case internal::WireFormatLite::CPPTYPE_FLOAT:
- return field->default_value_float() == 0;
- case internal::WireFormatLite::CPPTYPE_DOUBLE:
- return field->default_value_double() == 0;
- case internal::WireFormatLite::CPPTYPE_BOOL:
- return field->default_value_bool() == false;
- default:
- return false;
- }
-}
-
void MessageGenerator::
GenerateDependentBaseClassDefinition(io::Printer* printer) {
if (!use_dependent_base_) {
@@ -1009,19 +1098,11 @@ GenerateClassDefinition(io::Printer* printer) {
"\n");
}
- if (!StaticInitializersForced(descriptor_->file(), options_)) {
- printer->Print(vars,
- "#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
- "// Returns the internal default instance pointer. This function can\n"
- "// return NULL thus should not be used by the user. This is intended\n"
- "// for Protobuf internal code. Please use default_instance() declared\n"
- "// above instead.\n"
- "static inline const $classname$* internal_default_instance() {\n"
- " return default_instance_;\n"
- "}\n"
- "#endif\n"
+ // TODO(gerbens) make this private, while still granting other protos access.
+ printer->Print(
+ vars,
+ "static const $classname$* internal_default_instance();\n"
"\n");
- }
if (SupportsArenas(descriptor_)) {
@@ -1068,7 +1149,7 @@ GenerateClassDefinition(io::Printer* printer) {
"void Clear();\n"
"bool IsInitialized() const;\n"
"\n"
- "int ByteSize() const;\n"
+ "size_t ByteSizeLong() const;\n"
"bool MergePartialFromCodedStream(\n"
" ::google::protobuf::io::CodedInputStream* input);\n"
"void SerializeWithCachedSizes(\n"
@@ -1131,7 +1212,8 @@ GenerateClassDefinition(io::Printer* printer) {
"void SharedCtor();\n"
"void SharedDtor();\n"
"void SetCachedSize(int size) const;\n"
- "void InternalSwap($classname$* other);\n",
+ "void InternalSwap($classname$* other);\n"
+ "void UnsafeMergeFrom(const $classname$& from);\n",
"classname", classname_);
if (SupportsArenas(descriptor_)) {
printer->Print(
@@ -1260,8 +1342,8 @@ GenerateClassDefinition(io::Printer* printer) {
!descriptor_->options().message_set_wire_format() &&
num_required_fields_ > 1) {
printer->Print(
- "// helper for ByteSize()\n"
- "int RequiredFieldsByteSizeFallback() const;\n\n");
+ "// helper for ByteSizeLong()\n"
+ "size_t RequiredFieldsByteSizeFallback() const;\n\n");
}
// Prepare decls for _cached_size_ and _has_bits_. Their position in the
@@ -1271,18 +1353,10 @@ GenerateClassDefinition(io::Printer* printer) {
// TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it.
const string cached_size_decl = "mutable int _cached_size_;\n";
- // TODO(jieluo) - Optimize _has_bits_ for repeated and oneof fields.
- size_t sizeof_has_bits = (descriptor_->field_count() + 31) / 32 * 4;
- if (descriptor_->field_count() == 0) {
- // Zero-size arrays aren't technically allowed, and MSVC in particular
- // doesn't like them. We still need to declare these arrays to make
- // other code compile. Since this is an uncommon case, we'll just declare
- // them with size 1 and waste some space. Oh well.
- sizeof_has_bits = 4;
- }
+ const size_t sizeof_has_bits = HasBitsSize(descriptor_);
const string has_bits_decl = sizeof_has_bits == 0 ? "" :
- "::google::protobuf::uint32 _has_bits_[" + SimpleItoa(sizeof_has_bits / 4) + "];\n";
-
+ "::google::protobuf::internal::HasBits<" + SimpleItoa(sizeof_has_bits / 4) +
+ "> _has_bits_;\n";
// To minimize padding, data members are divided into three sections:
// (1) members assumed to align to 8 bytes
@@ -1326,45 +1400,27 @@ GenerateClassDefinition(io::Printer* printer) {
printer->Print(cached_size_decl.c_str());
need_to_emit_cached_size = false;
}
- } else {
- // Without field presence, we need another way to disambiguate the default
- // instance, because the default instance's submessage fields (if any) store
- // pointers to the default instances of the submessages even when they
- // aren't present. Alternatives to this approach might be to (i) use a
- // tagged pointer on all message fields, setting a tag bit for "not really
- // present, just default instance"; or (ii) comparing |this| against the
- // return value from GeneratedMessageFactory::GetPrototype() in all
- // has_$field$() calls. However, both of these options are much more
- // expensive (in code size and CPU overhead) than just checking a field in
- // the message. Long-term, the best solution would be to rearchitect the
- // default instance design not to store pointers to submessage default
- // instances, and have reflection get those some other way; but that change
- // would have too much impact on proto2.
- printer->Print(
- "bool _is_default_instance_;\n");
}
// Field members:
// List fields which doesn't belong to any oneof
- vector<const FieldDescriptor*> fields;
hash_map<string, int> fieldname_to_chunk;
for (int i = 0; i < descriptor_->field_count(); i++) {
if (!descriptor_->field(i)->containing_oneof()) {
const FieldDescriptor* field = descriptor_->field(i);
- fields.push_back(field);
fieldname_to_chunk[FieldName(field)] = i / 8;
}
}
- OptimizePadding(&fields);
+
// Emit some private and static members
runs_of_fields_ = vector< vector<string> >(1);
- for (int i = 0; i < fields.size(); ++i) {
- const FieldDescriptor* field = fields[i];
+ for (int i = 0; i < optimized_order_.size(); ++i) {
+ const FieldDescriptor* field = optimized_order_[i];
const FieldGenerator& generator = field_generators_.get(field);
generator.GenerateStaticMembers(printer);
generator.GeneratePrivateMembers(printer);
- if (CanClearByZeroing(field)) {
+ if (CanInitializeByZeroing(field)) {
const string& fieldname = FieldName(field);
if (!runs_of_fields_.back().empty() &&
(fieldname_to_chunk[runs_of_fields_.back().back()] !=
@@ -1424,15 +1480,15 @@ GenerateClassDefinition(io::Printer* printer) {
// Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
// friends so that they can access private static variables like
// default_instance_ and reflection_.
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- "friend void $dllexport_decl$ $adddescriptorsname$();\n",
- // Without.
- "friend void $dllexport_decl$ $adddescriptorsname$_impl();\n",
- // Vars.
- "dllexport_decl", options_.dllexport_decl, "adddescriptorsname",
- GlobalAddDescriptorsName(descriptor_->file()->name()));
+ printer->Print("friend void $dllexport_decl$ $initdefaultsname$_impl();\n",
+ // Vars.
+ "dllexport_decl", options_.dllexport_decl, "initdefaultsname",
+ GlobalInitDefaultsName(descriptor_->file()->name()));
+ printer->Print("friend void $dllexport_decl$ $adddescriptorsname$_impl();\n",
+ // Vars.
+ "dllexport_decl", options_.dllexport_decl,
+ "adddescriptorsname",
+ GlobalAddDescriptorsName(descriptor_->file()->name()));
printer->Print(
"friend void $assigndescriptorsname$();\n"
@@ -1443,12 +1499,22 @@ GenerateClassDefinition(io::Printer* printer) {
"shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
printer->Print(
- "void InitAsDefaultInstance();\n"
- "static $classname$* default_instance_;\n",
- "classname", classname_);
+ "void InitAsDefaultInstance();\n",
+ "classname", classname_);
printer->Outdent();
- printer->Print(vars, "};");
+ printer->Print("};\n");
+
+ // This should ideally be put into the class scope, but Visual Studio just
+ // refuses to compile it and complains about "use of undefined XXX":
+ // https://ci.appveyor.com/project/protobuf/protobuf/build/1.0.2673/job/nrdf4tb9dau0sck5
+ // A program as simple as "struct X { enum { value = sizeof(X) }; };" will
+ // trigger the same error.
+ printer->Print(
+ "extern ::google::protobuf::internal::ExplicitlyConstructed<$classname$> "
+ "$classname$_default_instance_;\n",
+ "classname", classname_);
+
GOOGLE_DCHECK(!need_to_emit_cached_size);
}
@@ -1499,6 +1565,12 @@ GenerateInlineMethods(io::Printer* printer, bool is_inline) {
"_oneof_case_[$oneof_index$]);\n"
"}\n");
}
+
+ printer->Print(
+ "inline const $classname$* $classname$::internal_default_instance() {\n"
+ " return &$classname$_default_instance_.get();\n"
+ "}\n",
+ "classname", classname_);
}
void MessageGenerator::
@@ -1578,18 +1650,18 @@ GenerateDescriptorInitializer(io::Printer* printer, int index) {
"::NewGeneratedMessageReflection";
// Construct the reflection object.
printer->Print(vars,
- "$classname$_reflection_ =\n"
- " $fn$(\n"
- " $classname$_descriptor_,\n"
- " $classname$::default_instance_,\n"
- " $classname$_offsets_,\n");
+ "$classname$_reflection_ =\n"
+ " $fn$(\n"
+ " $classname$_descriptor_,\n"
+ " $classname$::internal_default_instance(),\n"
+ " $classname$_offsets_,\n");
if (!HasFieldPresence(descriptor_->file())) {
// If we don't have field presence, then _has_bits_ does not exist.
printer->Print(vars,
" -1,\n");
} else {
printer->Print(vars,
- " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n");
+ " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_),\n");
}
// Unknown field offset: either points to the unknown field set if embedded
@@ -1637,22 +1709,12 @@ GenerateDescriptorInitializer(io::Printer* printer, int index) {
// not (because e.g. we don't have an unknown field set).
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(vars,
- " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
- "$classname$, _internal_metadata_),\n");
- } else {
- printer->Print(vars,
- " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
- "$classname$, _arena_),\n");
- }
-
- // is_default_instance_ offset.
- if (HasFieldPresence(descriptor_->file())) {
- printer->Print(vars,
- " -1);\n");
+ " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
+ "$classname$, _internal_metadata_));\n");
} else {
printer->Print(vars,
- " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
- "$classname$, _is_default_instance_));\n");
+ " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
+ "$classname$, _arena_));\n");
}
// Handle nested types.
@@ -1670,11 +1732,11 @@ GenerateTypeRegistrations(io::Printer* printer) {
// Register this message type with the message factory.
if (!IsMapEntryMessage(descriptor_)) {
printer->Print(
- "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
- " $classname$_descriptor_, &$classname$::default_instance());\n",
- "classname", classname_);
- }
- else {
+ "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
+ " $classname$_descriptor_, "
+ "$classname$::internal_default_instance());\n",
+ "classname", classname_);
+ } else {
map<string, string> vars;
CollectMapInfo(descriptor_, &vars);
vars["classname"] = classname_;
@@ -1708,6 +1770,12 @@ GenerateTypeRegistrations(io::Printer* printer) {
void MessageGenerator::
GenerateDefaultInstanceAllocator(io::Printer* printer) {
+ // Force initialization of primitive values we depend on.
+ printer->Print(
+ StrCat(
+ uses_string_ ? "::google::protobuf::internal::GetEmptyString();\n" : "")
+ .c_str());
+
// Construct the default instances of all fields, as they will be used
// when creating the default instance of the entire message.
for (int i = 0; i < descriptor_->field_count(); i++) {
@@ -1720,9 +1788,8 @@ GenerateDefaultInstanceAllocator(io::Printer* printer) {
// Construct the default instance. We can't call InitAsDefaultInstance() yet
// because we need to make sure all default instances that this one might
// depend on are constructed first.
- printer->Print(
- "$classname$::default_instance_ = new $classname$();\n",
- "classname", classname_);
+ printer->Print("$classname$_default_instance_.DefaultConstruct();\n",
+ "classname", classname_);
if ((descriptor_->oneof_decl_count() > 0) &&
HasDescriptorMethods(descriptor_->file(), options_)) {
@@ -1741,8 +1808,9 @@ GenerateDefaultInstanceAllocator(io::Printer* printer) {
void MessageGenerator::
GenerateDefaultInstanceInitializer(io::Printer* printer) {
printer->Print(
- "$classname$::default_instance_->InitAsDefaultInstance();\n",
- "classname", classname_);
+ "$classname$_default_instance_.get_mutable()->InitAsDefaultInstance();"
+ "\n",
+ "classname", classname_);
// Register extensions.
for (int i = 0; i < descriptor_->extension_count(); i++) {
@@ -1762,9 +1830,8 @@ GenerateDefaultInstanceInitializer(io::Printer* printer) {
void MessageGenerator::
GenerateShutdownCode(io::Printer* printer) {
printer->Print(
- "delete $classname$::default_instance_;\n",
- "classname", classname_);
-
+ "$classname$_default_instance_.Shutdown();\n",
+ "classname", classname_);
if (HasDescriptorMethods(descriptor_->file(), options_)) {
if (descriptor_->oneof_decl_count() > 0) {
printer->Print(
@@ -1894,6 +1961,12 @@ GenerateClassMethods(io::Printer* printer) {
GenerateIsInitialized(printer);
printer->Print("\n");
+ } else {
+ printer->Print(
+ "void $classname$::UnsafeMergeFrom(const $classname$& from) {\n"
+ " MergeFrom(from);\n"
+ "}\n",
+ "classname", classname_);
}
GenerateSwap(printer);
@@ -1966,15 +2039,15 @@ GenerateSharedConstructorCode(io::Printer* printer) {
"classname", classname_);
printer->Indent();
- if (!HasFieldPresence(descriptor_->file())) {
- printer->Print(
- " _is_default_instance_ = false;\n");
+ 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(descriptor_) % 8) != 0) {
+ printer->Print("_cached_size_ = 0;\n");
+ need_to_clear_cached_size = false;
}
- printer->Print(StrCat(
- uses_string_ ? "::google::protobuf::internal::GetEmptyString();\n" : "",
- "_cached_size_ = 0;\n").c_str());
-
if (PreserveUnknownFields(descriptor_) &&
!UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(
@@ -1982,16 +2055,52 @@ GenerateSharedConstructorCode(io::Printer* printer) {
" &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n");
}
- for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
- field_generators_.get(descriptor_->field(i))
- .GenerateConstructorCode(printer);
+ const FieldDescriptor* last_start = NULL;
+ // RunMap maps from fields that start each run to the number of fields in that
+ // run. This is optimized for the common case that there are very few runs in
+ // a message and that most of the eligible fields appear together.
+ typedef hash_map<const FieldDescriptor*, size_t> RunMap;
+ RunMap runs;
+
+ for (int i = 0; i < optimized_order_.size(); ++i) {
+ const FieldDescriptor* field = optimized_order_[i];
+ // TODO(ckennelly): Scalar messages (raw pointers) can be initialized by
+ // zero as well.
+ if (CanInitializeByZeroing(field)) {
+ if (last_start == NULL) {
+ last_start = field;
+ }
+
+ runs[last_start]++;
+ } else {
+ last_start = NULL;
}
}
- if (HasFieldPresence(descriptor_->file())) {
- printer->Print(
- "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
+ for (int i = 0; i < optimized_order_.size(); ++i) {
+ const FieldDescriptor* field = optimized_order_[i];
+ RunMap::const_iterator it = runs.find(field);
+
+ // We only apply the memset technique to runs of more than one field, as
+ // assignment is better than memset for generated code clarity.
+ if (it != runs.end() && it->second > 1) {
+ // Use a memset, then skip run_length fields.
+ const size_t run_length = it->second;
+ const string first_field_name = FieldName(field);
+ const string last_field_name =
+ FieldName(optimized_order_[i + run_length - 1]);
+
+ printer->Print(
+ "::memset(&$first$_, 0, reinterpret_cast<char*>(&$last$_) -\n"
+ " reinterpret_cast<char*>(&$first$_) + sizeof($last$_));\n",
+ "first", first_field_name,
+ "last", last_field_name);
+
+ i += run_length - 1;
+ // ++i at the top of the loop.
+ } else {
+ field_generators_.get(field).GenerateConstructorCode(printer);
+ }
}
for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
@@ -2000,6 +2109,10 @@ 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");
}
@@ -2013,7 +2126,8 @@ GenerateSharedDestructorCode(io::Printer* printer) {
if (SupportsArenas(descriptor_)) {
// Do nothing when the message is allocated in an arena.
printer->Print(
- "if (GetArenaNoVirtual() != NULL) {\n"
+ "::google::protobuf::Arena* arena = GetArenaNoVirtual();\n"
+ "if (arena != NULL) {\n"
" return;\n"
"}\n"
"\n");
@@ -2026,7 +2140,7 @@ GenerateSharedDestructorCode(io::Printer* printer) {
printer->Print(
"_unknown_fields_.Destroy(\n"
" &::google::protobuf::internal::GetEmptyStringAlreadyInited(),\n"
- " GetArenaNoVirtual());\n");
+ " arena);\n");
} else {
printer->Print(
"_unknown_fields_.DestroyNoArena(\n"
@@ -2035,11 +2149,10 @@ GenerateSharedDestructorCode(io::Printer* printer) {
}
// Write the destructors for each field except oneof members.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- if (!descriptor_->field(i)->containing_oneof()) {
- field_generators_.get(descriptor_->field(i))
- .GenerateDestructorCode(printer);
- }
+ // optimized_order_ does not contain oneof fields.
+ for (int i = 0; i < optimized_order_.size(); i++) {
+ const FieldDescriptor* field = optimized_order_[i];
+ field_generators_.get(field).GenerateDestructorCode(printer);
}
// Generate code to destruct oneofs. Clearing should do the work.
@@ -2051,17 +2164,11 @@ GenerateSharedDestructorCode(io::Printer* printer) {
"oneof_name", descriptor_->oneof_decl(i)->name());
}
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- "if (this != default_instance_) {\n",
- // Without.
- "if (this != &default_instance()) {\n");
-
// We need to delete all embedded messages.
// TODO(kenton): If we make unset messages point at default instances
// instead of NULL, then it would make sense to move this code into
// MessageFieldGenerator::GenerateDestructorCode().
+ bool need_delete_message_field = false;
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
@@ -2069,16 +2176,25 @@ GenerateSharedDestructorCode(io::Printer* printer) {
field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
// Skip oneof members
if (!field->containing_oneof()) {
- printer->Print(
- " delete $name$_;\n",
- "name", FieldName(field));
+ if (!need_delete_message_field) {
+ need_delete_message_field = true;
+ printer->Print(
+ "if (this != &$classname$_default_instance_.get()) {\n",
+ "classname", classname_);
+ printer->Indent();
+ }
+ printer->Print("delete $name$_;\n", "name", FieldName(field));
}
}
}
+ if (need_delete_message_field) {
+ printer->Outdent();
+ printer->Print(
+ "}\n");
+ }
printer->Outdent();
printer->Print(
- " }\n"
"}\n"
"\n");
}
@@ -2151,16 +2267,18 @@ GenerateStructors(io::Printer* printer) {
}
// Initialize member variables with arena constructor.
- for (int i = 0; i < descriptor_->field_count(); i++) {
- bool has_arena_constructor = descriptor_->field(i)->is_repeated();
+ for (int i = 0; i < optimized_order_.size(); i++) {
+ const FieldDescriptor* field = optimized_order_[i];
+
+ bool has_arena_constructor = field->is_repeated();
if (has_arena_constructor) {
initializer_with_arena += string(",\n ") +
- FieldName(descriptor_->field(i)) + string("_(arena)");
+ FieldName(field) + string("_(arena)");
}
}
if (IsAnyMessage(descriptor_)) {
- initializer_with_arena += ",\n _any_metadata_(&type_url, &value_)";
+ initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)";
}
string initializer_null;
@@ -2173,27 +2291,31 @@ GenerateStructors(io::Printer* printer) {
printer->Print(
"$classname$::$classname$()\n"
" : $superclass$()$initializer$ {\n"
+ " if (this != internal_default_instance()) $initdefaultsname$();\n"
" SharedCtor();\n"
" // @@protoc_insertion_point(constructor:$full_name$)\n"
"}\n",
- "classname", classname_,
- "superclass", superclass,
- "full_name", descriptor_->full_name(),
- "initializer", initializer_null);
+ "classname", classname_, "superclass", superclass, "full_name",
+ descriptor_->full_name(), "initializer", initializer_null,
+ "initdefaultsname", GlobalInitDefaultsName(descriptor_->file()->name()));
if (SupportsArenas(descriptor_)) {
printer->Print(
- "\n"
"$classname$::$classname$(::google::protobuf::Arena* arena)\n"
" : $initializer$ {\n"
+ // When arenas are used it's safe to assume we have finished
+ // static init time (protos with arenas are unsafe during static init)
+ "#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
+ " $initdefaultsname$();\n"
+ "#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
" SharedCtor();\n"
" RegisterArenaDtor(arena);\n"
" // @@protoc_insertion_point(arena_constructor:$full_name$)\n"
"}\n",
- "initializer", initializer_with_arena,
- "classname", classname_,
- "superclass", superclass,
- "full_name", descriptor_->full_name());
+ "initializer", initializer_with_arena, "classname", classname_,
+ "superclass", superclass, "full_name", descriptor_->full_name(),
+ "initdefaultsname",
+ GlobalInitDefaultsName(descriptor_->file()->name()));
}
printer->Print(
@@ -2201,11 +2323,6 @@ GenerateStructors(io::Printer* printer) {
"void $classname$::InitAsDefaultInstance() {\n",
"classname", classname_);
- if (!HasFieldPresence(descriptor_->file())) {
- printer->Print(
- " _is_default_instance_ = true;\n");
- }
-
// The default instance needs all of its embedded message pointers
// cross-linked to other default instances. We can't do this initialization
// in the constructor because some other default instances may not have been
@@ -2224,11 +2341,7 @@ GenerateStructors(io::Printer* printer) {
name = classname_ + "_default_oneof_instance_->";
}
name += FieldName(field);
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- " $name$_ = const_cast< $type$*>(&$type$::default_instance());\n",
- // Without.
+ printer->Print(
" $name$_ = const_cast< $type$*>(\n"
" $type$::internal_default_instance());\n",
// Vars.
@@ -2262,7 +2375,7 @@ GenerateStructors(io::Printer* printer) {
printer->Print(" {\n");
printer->Print(
" SharedCtor();\n"
- " MergeFrom(from);\n"
+ " UnsafeMergeFrom(from);\n"
" // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
"}\n"
"\n",
@@ -2304,37 +2417,29 @@ GenerateStructors(io::Printer* printer) {
if (HasDescriptorMethods(descriptor_->file(), options_) &&
!descriptor_->options().no_standard_descriptor_accessor()) {
printer->Print(
- "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
- " protobuf_AssignDescriptorsOnce();\n"
- " return $classname$_descriptor_;\n"
- "}\n"
- "\n",
- "classname", classname_,
- "adddescriptorsname",
- GlobalAddDescriptorsName(descriptor_->file()->name()));
+ "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
+ " protobuf_AssignDescriptorsOnce();\n"
+ " return $classname$_descriptor_;\n"
+ "}\n"
+ "\n",
+ "classname", classname_, "initdefaultsname",
+ GlobalInitDefaultsName(descriptor_->file()->name()));
}
printer->Print(
- "const $classname$& $classname$::default_instance() {\n",
- "classname", classname_);
-
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- " if (default_instance_ == NULL) $adddescriptorsname$();\n",
- // Without.
- " $adddescriptorsname$();\n",
- // Vars.
- "adddescriptorsname",
- GlobalAddDescriptorsName(descriptor_->file()->name()));
+ "const $classname$& $classname$::default_instance() {\n"
+ " $initdefaultsname$();\n"
+ " return *internal_default_instance();\n"
+ "}\n",
+ "classname", classname_, "initdefaultsname",
+ GlobalInitDefaultsName(descriptor_->file()->name()));
printer->Print(
- " return *default_instance_;\n"
- "}\n"
- "\n"
- "$classname$* $classname$::default_instance_ = NULL;\n"
- "\n",
- "classname", classname_);
+ "\n"
+ "::google::protobuf::internal::ExplicitlyConstructed<$classname$> "
+ "$classname$_default_instance_;\n"
+ "\n",
+ "classname", classname_);
if (SupportsArenas(descriptor_)) {
printer->Print(
@@ -2419,7 +2524,7 @@ GenerateClear(io::Printer* printer) {
" &reinterpret_cast<$classname$*>(16)->f)\n"
"#endif\n\n"
"#define ZR_(first, last) do {\\\n"
- " ::memset(&first, 0,\\\n"
+ " ::memset(&(first), 0,\\\n"
" ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\\\n"
"} while (0)\n\n";
for (int i = 0; i < runs_of_fields_.size(); i++) {
@@ -2463,7 +2568,7 @@ GenerateClear(io::Printer* printer) {
int count = popcnt(mask);
GOOGLE_DCHECK_GE(count, 1);
if (count == 1 ||
- (count <= 4 && count == memset_field_count_for_chunk[i / 8])) {
+ count == memset_field_count_for_chunk[i / 8]) {
// No "if" here because the chunk is trivial.
} else {
if (HasFieldPresence(descriptor_->file())) {
@@ -2540,8 +2645,7 @@ GenerateClear(io::Printer* printer) {
if (HasFieldPresence(descriptor_->file())) {
// Step 5: Everything else.
- printer->Print(
- "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
+ printer->Print("_has_bits_.Clear();\n");
}
if (PreserveUnknownFields(descriptor_)) {
@@ -2584,7 +2688,7 @@ GenerateOneofClear(io::Printer* printer) {
"$full_name$)\n");
printer->Indent();
printer->Print(oneof_vars,
- "switch($oneofname$_case()) {\n");
+ "switch ($oneofname$_case()) {\n");
printer->Indent();
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
@@ -2639,7 +2743,7 @@ GenerateSwap(io::Printer* printer) {
" InternalSwap(other);\n"
" } else {\n"
" $classname$ temp;\n"
- " temp.MergeFrom(*this);\n"
+ " temp.UnsafeMergeFrom(*this);\n"
" CopyFrom(*other);\n"
" other->CopyFrom(temp);\n"
" }\n"
@@ -2715,9 +2819,7 @@ GenerateMergeFrom(io::Printer* printer) {
"void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
"// @@protoc_insertion_point(generalized_merge_from_start:"
"$full_name$)\n"
- " if (GOOGLE_PREDICT_FALSE(&from == this)) {\n"
- " ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);\n"
- " }\n",
+ " if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);\n",
"classname", classname_, "full_name", descriptor_->full_name());
printer->Indent();
@@ -2726,7 +2828,7 @@ GenerateMergeFrom(io::Printer* printer) {
// system, as the GOOGLE_CHECK above ensured that we have the same descriptor
// for each message.
printer->Print(
- "const $classname$* source = \n"
+ "const $classname$* source =\n"
" ::google::protobuf::internal::DynamicCastToGenerated<const $classname$>(\n"
" &from);\n"
"if (source == NULL) {\n"
@@ -2736,7 +2838,7 @@ GenerateMergeFrom(io::Printer* printer) {
"} else {\n"
"// @@protoc_insertion_point(generalized_merge_from_cast_success:"
"$full_name$)\n"
- " MergeFrom(*source);\n"
+ " UnsafeMergeFrom(*source);\n"
"}\n",
"classname", classname_, "full_name", descriptor_->full_name());
@@ -2758,9 +2860,15 @@ GenerateMergeFrom(io::Printer* printer) {
"void $classname$::MergeFrom(const $classname$& from) {\n"
"// @@protoc_insertion_point(class_specific_merge_from_start:"
"$full_name$)\n"
- " if (GOOGLE_PREDICT_FALSE(&from == this)) {\n"
- " ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);\n"
- " }\n",
+ " if (GOOGLE_PREDICT_TRUE(&from != this)) {\n"
+ " UnsafeMergeFrom(from);\n"
+ " } else {\n"
+ " MergeFromFail(__LINE__);\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "void $classname$::UnsafeMergeFrom(const $classname$& from) {\n"
+ " GOOGLE_DCHECK(&from != this);\n",
"classname", classname_, "full_name", descriptor_->full_name());
printer->Indent();
@@ -2770,7 +2878,7 @@ GenerateMergeFrom(io::Printer* printer) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->is_repeated()) {
- field_generators_.get(field).GenerateMergingCode(printer);
+ field_generators_.get(field).GenerateUnsafeMergingCode(printer);
}
}
@@ -2865,7 +2973,8 @@ GenerateMergeFrom(io::Printer* printer) {
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(
"if (from._internal_metadata_.have_unknown_fields()) {\n"
- " mutable_unknown_fields()->MergeFrom(from.unknown_fields());\n"
+ " ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(\n"
+ " from.unknown_fields(), &_internal_metadata_);\n"
"}\n");
} else {
printer->Print(
@@ -2911,7 +3020,7 @@ GenerateCopyFrom(io::Printer* printer) {
printer->Print(
"if (&from == this) return;\n"
"Clear();\n"
- "MergeFrom(from);\n");
+ "UnsafeMergeFrom(from);\n");
printer->Outdent();
printer->Print("}\n");
@@ -2926,13 +3035,9 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
" ::google::protobuf::io::CodedInputStream* input) {\n",
"classname", classname_);
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- " return _extensions_.ParseMessageSet(input, default_instance_,\n"
- " mutable_unknown_fields());\n",
- // Without.
- " return _extensions_.ParseMessageSet(input, &default_instance(),\n"
+ printer->Print(
+ " return _extensions_.ParseMessageSet(input, "
+ "internal_default_instance(),\n"
" mutable_unknown_fields());\n",
// Vars.
"classname", classname_);
@@ -2956,7 +3061,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
// on the CodedOutputStream.
printer->Print(
" ::google::protobuf::io::LazyStringOutputStream unknown_fields_string(\n"
- " ::google::protobuf::internal::NewPermanentCallback(\n"
+ " ::google::protobuf::NewPermanentCallback(\n"
" &MutableUnknownFieldsFor$classname$, this));\n"
" ::google::protobuf::io::CodedOutputStream unknown_fields_stream(\n"
" &unknown_fields_string, false);\n",
@@ -2971,8 +3076,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Print("for (;;) {\n");
printer->Indent();
- google::protobuf::scoped_array<const FieldDescriptor * > ordered_fields(
- SortFieldsByNumber(descriptor_));
+ std::vector<const FieldDescriptor*> ordered_fields =
+ SortFieldsByNumber(descriptor_);
uint32 maxtag = descriptor_->field_count() == 0 ? 0 :
WireFormat::MakeTag(ordered_fields[descriptor_->field_count() - 1]);
const int kCutoff0 = 127; // fits in 1-byte varint
@@ -3000,7 +3105,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
// Find repeated messages and groups now, to simplify what follows.
hash_set<int> fields_with_parse_loop;
- for (int i = 0; i < descriptor_->field_count(); i++) {
+ for (int i = 0; i < ordered_fields.size(); i++) {
const FieldDescriptor* field = ordered_fields[i];
if (field->is_repeated() &&
(field->type() == FieldDescriptor::TYPE_MESSAGE ||
@@ -3012,7 +3117,13 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
// need_label is true if we generated "goto parse_$name$" while handling the
// previous field.
bool need_label = false;
- for (int i = 0; i < descriptor_->field_count(); i++) {
+ // Pay attention to whether we are in a run of fields from the same oneof.
+ // Motivation: it would be unusual to parse multiple values for a single
+ // oneof, since only the last would be used.
+ const FieldDescriptor* last_of_current_oneof = NULL;
+ // The following is valid iff last_of_current_oneof is non-NULL.
+ int index_of_last_of_current_oneof = -1;
+ for (int i = 0; i < ordered_fields.size(); i++) {
const FieldDescriptor* field = ordered_fields[i];
const bool loops = fields_with_parse_loop.count(i) > 0;
const bool next_field_loops = fields_with_parse_loop.count(i + 1) > 0;
@@ -3111,21 +3222,53 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
"input->UnsafeDecrementRecursionDepth();\n");
}
- // If there are more fields, expect the next one.
+ // If there are more fields, expect the next one, unless we just parsed
+ // a oneof and the next field would be from the same oneof. (There's no
+ // reason to expect something that makes what we just read irrelevant,
+ // so guess something after the current string of fields from this oneof.)
need_label = false;
if (!emitted_goto_next_tag) {
- if (i + 1 == descriptor_->field_count()) {
+ // delta is the distance in ordered_fields[] from the current field to
+ // the field we'll guess is next.
+ int delta = last_of_current_oneof == NULL
+ ? 1
+ : std::max(index_of_last_of_current_oneof - i, 1);
+ if (i == index_of_last_of_current_oneof) {
+ printer->Outdent();
+ printer->Print(
+ " after_$last$:\n",
+ "last", FieldName(last_of_current_oneof));
+ printer->Indent();
+ last_of_current_oneof = NULL;
+ } else if (last_of_current_oneof == NULL) {
+ delta = 1;
+ // Check for the unlikely case that delta > 1 is better.
+ if (field->containing_oneof() != NULL) {
+ while (i + delta < ordered_fields.size() &&
+ ordered_fields[i + delta]->containing_oneof() ==
+ field->containing_oneof()) {
+ index_of_last_of_current_oneof = i + delta;
+ last_of_current_oneof = ordered_fields[i + delta];
+ ++delta;
+ }
+ }
+ }
+ if (delta > 1) {
+ printer->Print(
+ "goto after_$last$;\n",
+ "last", FieldName(last_of_current_oneof));
+ } else if (i + delta == descriptor_->field_count()) {
// Expect EOF.
// TODO(kenton): Expect group end-tag?
printer->Print(
"if (input->ExpectAtEnd()) goto success;\n");
} else {
- const FieldDescriptor* next_field = ordered_fields[i + 1];
+ const FieldDescriptor* next_field = ordered_fields[i + delta];
printer->Print(
"if (input->ExpectTag($next_tag$)) goto parse_$next_name$;\n",
"next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
"next_name", next_field->name());
- need_label = true;
+ need_label = delta == 1;
}
}
@@ -3179,31 +3322,21 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
printer->Print(") {\n");
if (PreserveUnknownFields(descriptor_)) {
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- " DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
- " mutable_unknown_fields()));\n",
- // Without.
- " DO_(_extensions_.ParseField(tag, input, &default_instance(),\n"
+ printer->Print(
+ " DO_(_extensions_.ParseField(tag, input, "
+ "internal_default_instance(),\n"
" mutable_unknown_fields()));\n");
} else {
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
- // With static initializers.
- " DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
- " &unknown_fields_stream));\n",
- // Without.
- " DO_(_extensions_.ParseField(tag, input, &default_instance(),\n"
+ printer->Print(
+ " DO_(_extensions_.ParseField(tag, input, "
+ "internal_default_instance(),\n"
" &unknown_fields_stream));\n");
}
} else {
- PrintHandlingOptionalStaticInitializers(
- descriptor_->file(), options_, printer,
+ printer->Print(
// With static initializers.
- " DO_(_extensions_.ParseField(tag, input, default_instance_);\n",
- // Without.
- " DO_(_extensions_.ParseField(tag, input, &default_instance());\n");
+ " DO_(_extensions_.ParseField(tag, input, "
+ "internal_default_instance());\n");
}
printer->Print(
" continue;\n"
@@ -3248,6 +3381,43 @@ GenerateMergeFromCodedStream(io::Printer* printer) {
"}\n", "full_name", descriptor_->full_name());
}
+void MessageGenerator::GenerateSerializeOneofFields(
+ io::Printer* printer, const vector<const FieldDescriptor*>& fields,
+ bool to_array) {
+ GOOGLE_CHECK(!fields.empty());
+ if (fields.size() == 1) {
+ GenerateSerializeOneField(printer, fields[0], to_array);
+ return;
+ }
+ // We have multiple mutually exclusive choices. Emit a switch statement.
+ const OneofDescriptor* oneof = fields[0]->containing_oneof();
+ printer->Print(
+ "switch ($oneofname$_case()) {\n",
+ "oneofname", oneof->name());
+ printer->Indent();
+ for (int i = 0; i < fields.size(); i++) {
+ const FieldDescriptor* field = fields[i];
+ printer->Print(
+ "case k$field_name$:\n",
+ "field_name", UnderscoresToCamelCase(field->name(), true));
+ printer->Indent();
+ if (to_array) {
+ field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
+ printer);
+ } else {
+ field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
+ }
+ printer->Print(
+ "break;\n");
+ printer->Outdent();
+ }
+ printer->Outdent();
+ // Doing nothing is an option.
+ printer->Print(
+ " default: ;\n"
+ "}\n");
+}
+
void MessageGenerator::GenerateSerializeOneField(
io::Printer* printer, const FieldDescriptor* field, bool to_array) {
PrintFieldComment(printer, field);
@@ -3363,6 +3533,7 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
"classname", classname_);
printer->Indent();
+ printer->Print("(void)deterministic; // Unused\n");
printer->Print(
"// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n",
"full_name", descriptor_->full_name());
@@ -3381,10 +3552,61 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
void MessageGenerator::
GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
- google::protobuf::scoped_array<const FieldDescriptor * > ordered_fields(
- SortFieldsByNumber(descriptor_));
+ // If there are multiple fields in a row from the same oneof then we
+ // coalesce them and emit a switch statement. This is more efficient
+ // because it lets the C++ compiler know this is a "at most one can happen"
+ // situation. If we emitted "if (has_x()) ...; if (has_y()) ..." the C++
+ // compiler's emitted code might check has_y() even when has_x() is true.
+ class LazySerializerEmitter {
+ public:
+ LazySerializerEmitter(MessageGenerator* mg, io::Printer* printer,
+ bool to_array)
+ : mg_(mg),
+ printer_(printer),
+ to_array_(to_array),
+ eager_(!HasFieldPresence(mg->descriptor_->file())) {}
+
+ ~LazySerializerEmitter() { Flush(); }
+
+ // If conditions allow, try to accumulate a run of fields from the same
+ // oneof, and handle them at the next Flush().
+ void Emit(const FieldDescriptor* field) {
+ if (eager_ || MustFlush(field)) {
+ Flush();
+ }
+ if (field->containing_oneof() == NULL) {
+ mg_->GenerateSerializeOneField(printer_, field, to_array_);
+ } else {
+ v_.push_back(field);
+ }
+ }
+
+ void Flush() {
+ if (!v_.empty()) {
+ mg_->GenerateSerializeOneofFields(printer_, v_, to_array_);
+ v_.clear();
+ }
+ }
- vector<const Descriptor::ExtensionRange*> sorted_extensions;
+ private:
+ // If we have multiple fields in v_ then they all must be from the same
+ // oneof. Would adding field to v_ break that invariant?
+ bool MustFlush(const FieldDescriptor* field) {
+ return !v_.empty() &&
+ v_[0]->containing_oneof() != field->containing_oneof();
+ }
+
+ MessageGenerator* mg_;
+ io::Printer* printer_;
+ const bool to_array_;
+ const bool eager_;
+ vector<const FieldDescriptor*> v_;
+ };
+
+ std::vector<const FieldDescriptor*> ordered_fields =
+ SortFieldsByNumber(descriptor_);
+
+ 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));
}
@@ -3392,22 +3614,26 @@ GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
ExtensionRangeSorter());
// Merge the fields and the extension ranges, both sorted by field number.
- int i, j;
- for (i = 0, j = 0;
- i < descriptor_->field_count() || j < sorted_extensions.size();
- ) {
- if (i == descriptor_->field_count()) {
- GenerateSerializeOneExtensionRange(printer,
- sorted_extensions[j++],
- to_array);
- } else if (j == sorted_extensions.size()) {
- GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
- } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
- GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
- } else {
- GenerateSerializeOneExtensionRange(printer,
- sorted_extensions[j++],
- to_array);
+ {
+ LazySerializerEmitter e(this, printer, to_array);
+ int i, j;
+ for (i = 0, j = 0;
+ i < ordered_fields.size() || j < sorted_extensions.size();) {
+ if (i == descriptor_->field_count()) {
+ e.Flush();
+ GenerateSerializeOneExtensionRange(printer,
+ sorted_extensions[j++],
+ to_array);
+ } else if (j == sorted_extensions.size()) {
+ e.Emit(ordered_fields[i++]);
+ } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
+ e.Emit(ordered_fields[i++]);
+ } else {
+ e.Flush();
+ GenerateSerializeOneExtensionRange(printer,
+ sorted_extensions[j++],
+ to_array);
+ }
}
}
@@ -3479,9 +3705,9 @@ GenerateByteSize(io::Printer* printer) {
if (descriptor_->options().message_set_wire_format()) {
// Special-case MessageSet.
printer->Print(
- "int $classname$::ByteSize() const {\n"
+ "size_t $classname$::ByteSizeLong() const {\n"
"// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n"
- " int total_size = _extensions_.MessageSetByteSize();\n",
+ " size_t total_size = _extensions_.MessageSetByteSize();\n",
"classname", classname_, "full_name", descriptor_->full_name());
GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
printer->Print(
@@ -3490,8 +3716,9 @@ GenerateByteSize(io::Printer* printer) {
" ComputeUnknownMessageSetItemsSize(unknown_fields());\n"
"}\n");
printer->Print(
+ " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
" GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- " _cached_size_ = total_size;\n"
+ " _cached_size_ = cached_size;\n"
" GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
" return total_size;\n"
"}\n");
@@ -3502,12 +3729,12 @@ GenerateByteSize(io::Printer* printer) {
// Emit a function (rarely used, we hope) that handles the required fields
// by checking for each one individually.
printer->Print(
- "int $classname$::RequiredFieldsByteSizeFallback() const {\n"
+ "size_t $classname$::RequiredFieldsByteSizeFallback() const {\n"
"// @@protoc_insertion_point(required_fields_byte_size_fallback_start:"
"$full_name$)\n",
"classname", classname_, "full_name", descriptor_->full_name());
printer->Indent();
- printer->Print("int total_size = 0;\n");
+ printer->Print("size_t total_size = 0;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
if (field->is_required()) {
@@ -3528,12 +3755,12 @@ GenerateByteSize(io::Printer* printer) {
}
printer->Print(
- "int $classname$::ByteSize() const {\n"
+ "size_t $classname$::ByteSizeLong() const {\n"
"// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n",
"classname", classname_, "full_name", descriptor_->full_name());
printer->Indent();
printer->Print(
- "int total_size = 0;\n"
+ "size_t total_size = 0;\n"
"\n");
// Handle required fields (if any). We expect all of them to be
@@ -3726,8 +3953,9 @@ GenerateByteSize(io::Printer* printer) {
// exact same value, it works on all common processors. In a future version
// of C++, _cached_size_ should be made into an atomic<int>.
printer->Print(
+ "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- "_cached_size_ = total_size;\n"
+ "_cached_size_ = cached_size;\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
"return total_size;\n");
@@ -3803,7 +4031,9 @@ GenerateIsInitialized(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"\n"
- "if (!_extensions_.IsInitialized()) return false;");
+ "if (!_extensions_.IsInitialized()) {\n"
+ " return false;\n"
+ "}\n");
}
printer->Outdent();
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/cpp_message.h
index b1e3fe21..3bdc0ed3 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message.h
+++ b/src/google/protobuf/compiler/cpp/cpp_message.h
@@ -165,6 +165,11 @@ class MessageGenerator {
void GenerateSerializeOneField(io::Printer* printer,
const FieldDescriptor* field,
bool unbounded);
+ // Generate a switch statement to serialize 2+ fields from the same oneof.
+ // Or, if fields.size() == 1, just call GenerateSerializeOneField().
+ void GenerateSerializeOneofFields(
+ io::Printer* printer, const vector<const FieldDescriptor*>& fields,
+ bool to_array);
void GenerateSerializeOneExtensionRange(
io::Printer* printer, const Descriptor::ExtensionRange* range,
bool unbounded);
@@ -189,6 +194,11 @@ class MessageGenerator {
string classname_;
Options options_;
FieldGeneratorMap field_generators_;
+ // optimized_order_ is the order we layout the message's fields in the class.
+ // This is reused to initialize the fields in-order for cache efficiency.
+ //
+ // optimized_order_ excludes oneof fields.
+ vector<const FieldDescriptor *> optimized_order_;
vector< vector<string> > runs_of_fields_; // that might be trivially cleared
google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> > nested_generators_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
index d021035d..ca7bae02 100644
--- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_message_field.cc
@@ -161,8 +161,7 @@ void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions(
" if ($name$_ == NULL) {\n"
" return NULL;\n"
" } else {\n"
- " $type$* temp = new $type$;\n"
- " temp->MergeFrom(*$name$_);\n"
+ " $type$* temp = new $type$(*$name$_);\n"
" $name$_ = NULL;\n"
" return temp;\n"
" }\n"
@@ -346,23 +345,29 @@ GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const {
void MessageFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
+ if (dependent_field_) {
+ // for dependent fields we cannot access its internal_default_instance,
+ // because the type is incomplete.
+ // TODO(gerbens) deprecate dependent base class.
+ map<string, string> variables(variables_);
+ variables["inline"] = is_inline ? "inline " : "";
+ printer->Print(variables,
+ "$inline$const $type$& $classname$::$name$() const {\n"
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_ != NULL ? *$name$_\n"
+ " : *internal_default_instance()->$name$_;\n"
+ "}\n");
+ return;
+ }
+
map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$const $type$& $classname$::$name$() const {\n"
- " // @@protoc_insertion_point(field_get:$full_name$)\n");
-
- PrintHandlingOptionalStaticInitializers(
- variables, descriptor_->file(), options_, printer,
- // With static initializers.
- " return $name$_ != NULL ? *$name$_ : *default_instance_->$name$_;\n",
- // Without.
- " return $name$_ != NULL ? *$name$_ : *default_instance().$name$_;\n");
- printer->Print(variables, "}\n");
-
- if (dependent_field_) {
- return;
- }
+ " // @@protoc_insertion_point(field_get:$full_name$)\n"
+ " return $name$_ != NULL ? *$name$_\n"
+ " : *$type$::internal_default_instance();\n"
+ "}\n");
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
@@ -663,8 +668,8 @@ InternalGenerateInlineAccessorDefinitions(const map<string, string>& variables,
" if ($this_message$GetArenaNoVirtual() != NULL) {\n"
// N.B.: safe to use the underlying field pointer here because we are sure
// that it is non-NULL (because has_$name$() returned true).
- " $dependent_typename$* temp = new $dependent_typename$;\n"
- " temp->MergeFrom(*$field_member$);\n"
+ " $dependent_typename$* temp = "
+ "new $dependent_typename$(*$field_member$);\n"
" $field_member$ = NULL;\n"
" return temp;\n"
" } else {\n"
@@ -1041,12 +1046,18 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
void RepeatedMessageFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
- "total_size += $tag_size$ * this->$name$_size();\n"
- "for (int i = 0; i < this->$name$_size(); i++) {\n"
+ "{\n"
+ " unsigned int count = this->$name$_size();\n");
+ printer->Indent();
+ printer->Print(variables_,
+ "total_size += $tag_size$UL * count;\n"
+ "for (unsigned int i = 0; i < count; i++) {\n"
" total_size +=\n"
" ::google::protobuf::internal::WireFormatLite::$declared_type$SizeNoVirtual(\n"
" this->$name$(i));\n"
"}\n");
+ printer->Outdent();
+ printer->Print("}\n");
}
} // namespace cpp
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
index 650f0381..54b3d24a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc
@@ -123,13 +123,13 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
void PrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ $type$ $classname$::$name$() const {\n"
+ "$inline$$type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$ void $classname$::set_$name$($type$ value) {\n"
+ "$inline$void $classname$::set_$name$($type$ value) {\n"
" $set_hasbit$\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
@@ -159,10 +159,10 @@ GenerateConstructorCode(io::Printer* printer) const {
void PrimitiveFieldGenerator::
GenerateMergeFromCodedStream(io::Printer* printer) const {
printer->Print(variables_,
+ "$set_hasbit$\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" $type$, $wire_format_field_type$>(\n"
- " input, &$name$_)));\n"
- "$set_hasbit$\n");
+ " input, &$name$_)));\n");
}
void PrimitiveFieldGenerator::
@@ -207,16 +207,16 @@ PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
void PrimitiveOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ $type$ $classname$::$name$() const {\n"
+ "$inline$$type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_;\n"
" }\n"
" return $default$;\n"
"}\n"
- "$inline$ void $classname$::set_$name$($type$ value) {\n"
+ "$inline$void $classname$::set_$name$($type$ value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -298,27 +298,27 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
void RepeatedPrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ $type$ $classname$::$name$(int index) const {\n"
+ "$inline$$type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get(index);\n"
"}\n"
- "$inline$ void $classname$::set_$name$(int index, $type$ value) {\n"
+ "$inline$void $classname$::set_$name$(int index, $type$ value) {\n"
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::add_$name$($type$ value) {\n"
+ "$inline$void $classname$::add_$name$($type$ value) {\n"
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n");
printer->Print(variables,
- "$inline$ const ::google::protobuf::RepeatedField< $type$ >&\n"
+ "$inline$const ::google::protobuf::RepeatedField< $type$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$ ::google::protobuf::RepeatedField< $type$ >*\n"
+ "$inline$::google::protobuf::RepeatedField< $type$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -336,6 +336,11 @@ GenerateMergingCode(io::Printer* printer) const {
}
void RepeatedPrimitiveFieldGenerator::
+GenerateUnsafeMergingCode(io::Printer* printer) const {
+ printer->Print(variables_, "$name$_.UnsafeMergeFrom(from.$name$_);\n");
+}
+
+void RepeatedPrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
}
@@ -420,18 +425,19 @@ void RepeatedPrimitiveFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
- " int data_size = 0;\n");
+ " size_t data_size = 0;\n"
+ " unsigned int count = this->$name$_size();\n");
printer->Indent();
int fixed_size = FixedSize(descriptor_->type());
if (fixed_size == -1) {
printer->Print(variables_,
- "for (int i = 0; i < this->$name$_size(); i++) {\n"
+ "for (unsigned int i = 0; i < count; i++) {\n"
" data_size += ::google::protobuf::internal::WireFormatLite::\n"
" $declared_type$Size(this->$name$(i));\n"
"}\n");
} else {
printer->Print(variables_,
- "data_size = $fixed_size$ * this->$name$_size();\n");
+ "data_size = $fixed_size$UL * count;\n");
}
if (descriptor_->is_packed()) {
@@ -440,13 +446,16 @@ GenerateByteSize(io::Printer* printer) const {
" total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
"}\n"
+ "int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
- "_$name$_cached_byte_size_ = data_size;\n"
+ "_$name$_cached_byte_size_ = cached_size;\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
"total_size += data_size;\n");
} else {
printer->Print(variables_,
- "total_size += $tag_size$ * this->$name$_size() + data_size;\n");
+ "total_size += $tag_size$ *\n"
+ " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
+ "total_size += data_size;\n");
}
printer->Outdent();
printer->Print("}\n");
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
index 655ebde4..23cc697e 100644
--- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_primitive_field.h
@@ -103,6 +103,7 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
bool is_inline) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
+ virtual void GenerateUnsafeMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
index 1d743457..aee3d1ea 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.cc
@@ -166,25 +166,25 @@ void StringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
- "$inline$ const ::std::string& $classname$::$name$() const {\n"
+ "$inline$const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get($default_variable$);\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const ::std::string& value) {\n"
+ "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.Set($default_variable$, value, GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const char* value) {\n"
+ "$inline$void $classname$::set_$name$(const char* value) {\n"
" $set_hasbit$\n"
" $name$_.Set($default_variable$, $string_piece$(value),\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$ "
+ "$inline$"
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
" $set_hasbit$\n"
@@ -192,24 +192,24 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$ ::std::string* $classname$::mutable_$name$() {\n"
+ "$inline$::std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
"}\n"
- "$inline$ ::std::string* $classname$::$release_name$() {\n"
+ "$inline$::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
" return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"
"}\n"
- "$inline$ ::std::string* $classname$::unsafe_arena_release_$name$() {\n"
+ "$inline$::std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" $clear_hasbit$\n"
" return $name$_.UnsafeArenaRelease($default_variable$,\n"
" GetArenaNoVirtual());\n"
"}\n"
- "$inline$ void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -219,7 +219,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::unsafe_arena_set_allocated_$name$(\n"
+ "$inline$void $classname$::unsafe_arena_set_allocated_$name$(\n"
" ::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if ($name$ != NULL) {\n"
@@ -235,21 +235,21 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
} else {
// No-arena case.
printer->Print(variables,
- "$inline$ const ::std::string& $classname$::$name$() const {\n"
+ "$inline$const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.GetNoArena($default_variable$);\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const ::std::string& value) {\n"
+ "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const char* value) {\n"
+ "$inline$void $classname$::set_$name$(const char* value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$ "
+ "$inline$"
"void $classname$::set_$name$(const $pointer_type$* value, "
"size_t size) {\n"
" $set_hasbit$\n"
@@ -257,17 +257,17 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$ ::std::string* $classname$::mutable_$name$() {\n"
+ "$inline$::std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.MutableNoArena($default_variable$);\n"
"}\n"
- "$inline$ ::std::string* $classname$::$release_name$() {\n"
+ "$inline$::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
" return $name$_.ReleaseNoArena($default_variable$);\n"
"}\n"
- "$inline$ void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -339,8 +339,10 @@ GenerateConstructorCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
+ // The variable |arena| is defined by the enclosing code.
+ // See MessageGenerator::GenerateSharedDestructorCode.
printer->Print(variables_,
- "$name$_.Destroy($default_variable$, GetArenaNoVirtual());\n");
+ "$name$_.Destroy($default_variable$, arena);\n");
} else {
printer->Print(variables_,
"$name$_.DestroyNoArena($default_variable$);\n");
@@ -426,17 +428,17 @@ void StringOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
- "$inline$ const ::std::string& $classname$::$name$() const {\n"
+ "$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($default_variable$);\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const ::std::string& value) {\n"
+ "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -446,7 +448,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const char* value) {\n"
+ "$inline$void $classname$::set_$name$(const char* value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -456,7 +458,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$ "
+ "$inline$"
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
" if (!has_$name$()) {\n"
@@ -469,7 +471,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$ ::std::string* $classname$::mutable_$name$() {\n"
+ "$inline$::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -479,7 +481,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
- "$inline$ ::std::string* $classname$::$release_name$() {\n"
+ "$inline$::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@@ -489,7 +491,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
- "$inline$ ::std::string* $classname$::unsafe_arena_release_$name$() {\n"
+ "$inline$::std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (has_$name$()) {\n"
@@ -500,7 +502,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
- "$inline$ void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -512,7 +514,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::unsafe_arena_set_allocated_$name$("
+ "$inline$void $classname$::unsafe_arena_set_allocated_$name$("
"::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (!has_$name$()) {\n"
@@ -530,14 +532,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
} else {
// No-arena case.
printer->Print(variables,
- "$inline$ const ::std::string& $classname$::$name$() const {\n"
+ "$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($default_variable$);\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const ::std::string& value) {\n"
+ "$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -547,7 +549,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $oneof_prefix$$name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::set_$name$(const char* value) {\n"
+ "$inline$void $classname$::set_$name$(const char* value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -557,7 +559,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$ "
+ "$inline$"
"void $classname$::set_$name$(const $pointer_type$* value, size_t size) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -568,7 +570,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$ ::std::string* $classname$::mutable_$name$() {\n"
+ "$inline$::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -577,7 +579,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $oneof_prefix$$name$_.MutableNoArena($default_variable$);\n"
"}\n"
- "$inline$ ::std::string* $classname$::$release_name$() {\n"
+ "$inline$::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
@@ -586,7 +588,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
- "$inline$ void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
+ "$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -732,55 +734,55 @@ void RepeatedStringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
map<string, string> variables(variables_);
- variables["inline"] = is_inline ? "inline" : "";
+ variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
- "$inline$ const ::std::string& $classname$::$name$(int index) const {\n"
+ "$inline$const ::std::string& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.$cppget$(index);\n"
"}\n"
- "$inline$ ::std::string* $classname$::mutable_$name$(int index) {\n"
+ "$inline$::std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
- "$inline$ void $classname$::set_$name$(int index, const ::std::string& value) {\n"
+ "$inline$void $classname$::set_$name$(int index, const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(value);\n"
"}\n"
- "$inline$ void $classname$::set_$name$(int index, const char* value) {\n"
+ "$inline$void $classname$::set_$name$(int index, const char* value) {\n"
" $name$_.Mutable(index)->assign(value);\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
- "$inline$ void "
+ "$inline$void "
"$classname$::set_$name$"
"(int index, const $pointer_type$* value, size_t size) {\n"
" $name$_.Mutable(index)->assign(\n"
" reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
- "$inline$ ::std::string* $classname$::add_$name$() {\n"
+ "$inline$::std::string* $classname$::add_$name$() {\n"
" // @@protoc_insertion_point(field_add_mutable:$full_name$)\n"
" return $name$_.Add();\n"
"}\n"
- "$inline$ void $classname$::add_$name$(const ::std::string& value) {\n"
+ "$inline$void $classname$::add_$name$(const ::std::string& value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
- "$inline$ void $classname$::add_$name$(const char* value) {\n"
+ "$inline$void $classname$::add_$name$(const char* value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add_char:$full_name$)\n"
"}\n"
- "$inline$ void "
+ "$inline$void "
"$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n"
" $name$_.Add()->assign(reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_add_pointer:$full_name$)\n"
"}\n");
printer->Print(variables,
- "$inline$ const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
+ "$inline$const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
- "$inline$ ::google::protobuf::RepeatedPtrField< ::std::string>*\n"
+ "$inline$::google::protobuf::RepeatedPtrField< ::std::string>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -798,6 +800,11 @@ GenerateMergingCode(io::Printer* printer) const {
}
void RepeatedStringFieldGenerator::
+GenerateUnsafeMergingCode(io::Printer* printer) const {
+ printer->Print(variables_, "$name$_.UnsafeMergeFrom(from.$name$_);\n");
+}
+
+void RepeatedStringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.UnsafeArenaSwap(&other->$name$_);\n");
}
@@ -858,7 +865,8 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
- "total_size += $tag_size$ * this->$name$_size();\n"
+ "total_size += $tag_size$ *\n"
+ " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
"for (int i = 0; i < this->$name$_size(); i++) {\n"
" total_size += ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"
" this->$name$(i));\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/cpp_string_field.h
index cb4e8772..1dea7663 100644
--- a/src/google/protobuf/compiler/cpp/cpp_string_field.h
+++ b/src/google/protobuf/compiler/cpp/cpp_string_field.h
@@ -110,6 +110,7 @@ class RepeatedStringFieldGenerator : public FieldGenerator {
bool is_inline) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
+ void GenerateUnsafeMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
index 5d82946d..d214ef0a 100644
--- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc
+++ b/src/google/protobuf/compiler/cpp/cpp_unittest.cc
@@ -129,12 +129,12 @@ TEST(GeneratedDescriptorTest, IdenticalDescriptors) {
// Test that descriptors are generated correctly by converting them to
// FileDescriptorProtos and comparing.
- FileDescriptorProto generated_decsriptor_proto, parsed_descriptor_proto;
- generated_descriptor->CopyTo(&generated_decsriptor_proto);
+ 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_decsriptor_proto.DebugString());
+ generated_descriptor_proto.DebugString());
}
#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER)
@@ -1252,7 +1252,7 @@ class GeneratedServiceTest : public testing::Test {
foo_(descriptor_->FindMethodByName("Foo")),
bar_(descriptor_->FindMethodByName("Bar")),
stub_(&mock_channel_),
- done_(::google::protobuf::internal::NewPermanentCallback(&DoNothing)) {}
+ done_(NewPermanentCallback(&DoNothing)) {}
virtual void SetUp() {
ASSERT_TRUE(foo_ != NULL);
diff --git a/src/google/protobuf/compiler/csharp/csharp_generator.h b/src/google/protobuf/compiler/csharp/csharp_generator.h
index 9b54e914..fd41d852 100644
--- a/src/google/protobuf/compiler/csharp/csharp_generator.h
+++ b/src/google/protobuf/compiler/csharp/csharp_generator.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Generates C# code for a given .proto file.
+
#ifndef GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__
#define GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__
@@ -40,6 +42,10 @@ namespace protobuf {
namespace compiler {
namespace csharp {
+// CodeGenerator implementation which generates a C# source file and
+// header. If you create your own protocol compiler binary and you want
+// it to support C# output, you can do so by registering an instance of this
+// CodeGenerator with the CommandLineInterface in your main() function.
class LIBPROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
virtual bool Generate(
diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/java_file.cc
index 5e387285..3cbc530e 100644
--- a/src/google/protobuf/compiler/java/java_file.cc
+++ b/src/google/protobuf/compiler/java/java_file.cc
@@ -189,8 +189,6 @@ void MaybeRestartJavaMethod(io::Printer* printer,
*bytecode_estimate = 0;
}
}
-
-
} // namespace
FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options,
diff --git a/src/google/protobuf/compiler/java/java_map_field.cc b/src/google/protobuf/compiler/java/java_map_field.cc
index 16c5bec5..07aa3565 100644
--- a/src/google/protobuf/compiler/java/java_map_field.cc
+++ b/src/google/protobuf/compiler/java/java_map_field.cc
@@ -92,7 +92,11 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
const JavaType valueJavaType = GetJavaType(value);
(*variables)["key_type"] = TypeName(key, name_resolver, false);
- (*variables)["boxed_key_type"] = TypeName(key, name_resolver, true);
+ string boxed_key_type = TypeName(key, name_resolver, true);
+ (*variables)["boxed_key_type"] = boxed_key_type;
+ // Used for calling the serialization function.
+ (*variables)["short_key_type"] =
+ boxed_key_type.substr(boxed_key_type.rfind('.') + 1);
(*variables)["key_wire_type"] = WireType(key);
(*variables)["key_default_value"] = DefaultValue(key, true, name_resolver);
(*variables)["key_null_check"] = IsReferenceType(keyJavaType) ?
@@ -147,6 +151,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
name_resolver->GetImmutableClassName(descriptor->file()) +
".internal_" + UniqueFileScopeIdentifier(descriptor->message_type()) +
"_descriptor, ";
+ (*variables)["ver"] = GeneratedCodeVersionSuffix();
}
} // namespace
@@ -661,21 +666,23 @@ GenerateParsingCode(io::Printer* printer) const {
variables_,
"com.google.protobuf.ByteString bytes = input.readBytes();\n"
"com.google.protobuf.MapEntry<$type_parameters$>\n"
- "$name$ = $default_entry$.getParserForType().parseFrom(bytes);\n");
+ "$name$__ = $default_entry$.getParserForType().parseFrom(bytes);\n");
printer->Print(
variables_,
- "if ($value_enum_type$.forNumber($name$.getValue()) == null) {\n"
+ "if ($value_enum_type$.forNumber($name$__.getValue()) == null) {\n"
" unknownFields.mergeLengthDelimitedField($number$, bytes);\n"
"} else {\n"
- " $name$_.getMutableMap().put($name$.getKey(), $name$.getValue());\n"
+ " $name$_.getMutableMap().put(\n"
+ " $name$__.getKey(), $name$__.getValue());\n"
"}\n");
} else {
printer->Print(
variables_,
"com.google.protobuf.MapEntry<$type_parameters$>\n"
- "$name$ = input.readMessage(\n"
+ "$name$__ = input.readMessage(\n"
" $default_entry$.getParserForType(), extensionRegistry);\n"
- "$name$_.getMutableMap().put($name$.getKey(), $name$.getValue());\n");
+ "$name$_.getMutableMap().put(\n"
+ " $name$__.getKey(), $name$__.getValue());\n");
}
}
@@ -688,15 +695,12 @@ void ImmutableMapFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
printer->Print(
variables_,
- "for (java.util.Map.Entry<$type_parameters$> entry\n"
- " : internalGet$capitalized_name$().getMap().entrySet()) {\n"
- " com.google.protobuf.MapEntry<$type_parameters$>\n"
- " $name$ = $default_entry$.newBuilderForType()\n"
- " .setKey(entry.getKey())\n"
- " .setValue(entry.getValue())\n"
- " .build();\n"
- " output.writeMessage($number$, $name$);\n"
- "}\n");
+ "com.google.protobuf.GeneratedMessage$ver$\n"
+ " .serialize$short_key_type$MapTo(\n"
+ " output,\n"
+ " internalGet$capitalized_name$(),\n"
+ " $default_entry$,\n"
+ " $number$);\n");
}
void ImmutableMapFieldGenerator::
@@ -706,12 +710,12 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
"for (java.util.Map.Entry<$type_parameters$> entry\n"
" : internalGet$capitalized_name$().getMap().entrySet()) {\n"
" com.google.protobuf.MapEntry<$type_parameters$>\n"
- " $name$ = $default_entry$.newBuilderForType()\n"
+ " $name$__ = $default_entry$.newBuilderForType()\n"
" .setKey(entry.getKey())\n"
" .setValue(entry.getValue())\n"
" .build();\n"
" size += com.google.protobuf.CodedOutputStream\n"
- " .computeMessageSize($number$, $name$);\n"
+ " .computeMessageSize($number$, $name$__);\n"
"}\n");
}
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 0d3bea17..5f102e07 100644
--- a/src/google/protobuf/compiler/java/java_map_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_map_field_lite.cc
@@ -765,14 +765,14 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(
variables_,
"com.google.protobuf.ByteString bytes = input.readBytes();\n"
- "java.util.Map.Entry<$type_parameters$> $name$ =\n"
+ "java.util.Map.Entry<$type_parameters$> $name$__ =\n"
" $default_entry$.parseEntry(bytes, extensionRegistry);\n");
printer->Print(
variables_,
- "if ($value_enum_type$.forNumber($name$.getValue()) == null) {\n"
+ "if ($value_enum_type$.forNumber($name$__.getValue()) == null) {\n"
" super.mergeLengthDelimitedField($number$, bytes);\n"
"} else {\n"
- " $name$_.put($name$);\n"
+ " $name$_.put($name$__);\n"
"}\n");
} else {
printer->Print(
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc
index 6c80d070..68d28b05 100644
--- a/src/google/protobuf/compiler/java/java_message.cc
+++ b/src/google/protobuf/compiler/java/java_message.cc
@@ -928,7 +928,7 @@ void ImmutableMessageGenerator::GenerateIsInitialized(
case FieldDescriptor::LABEL_REPEATED:
if (IsMapEntry(field->message_type())) {
printer->Print(
- "for ($type$ item : get$name$().values()) {\n"
+ "for ($type$ item : get$name$Map().values()) {\n"
" if (!item.isInitialized()) {\n"
" memoizedIsInitialized = 0;\n"
" return false;\n"
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/java_message_builder.cc
index 42154694..cd82c51a 100644
--- a/src/google/protobuf/compiler/java/java_message_builder.cc
+++ b/src/google/protobuf/compiler/java/java_message_builder.cc
@@ -184,6 +184,11 @@ Generate(io::Printer* printer) {
"}\n"
"\n");
} else {
+ // Override methods declared in GeneratedMessage to return the concrete
+ // generated type so callsites won't depend on GeneratedMessage. This
+ // is needed to keep binary compatibility when we change generated code
+ // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
+ // we changed all generated code to subclass GeneratedMessageV3).
printer->Print(
"public final Builder setUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
@@ -456,6 +461,11 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
+ // Override methods declared in GeneratedMessage to return the concrete
+ // generated type so callsites won't depend on GeneratedMessage. This
+ // is needed to keep binary compatibility when we change generated code
+ // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
+ // we changed all generated code to subclass GeneratedMessageV3).
printer->Print(
"public Builder clone() {\n"
" return (Builder) super.clone();\n"
@@ -596,7 +606,6 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
" return this;\n"
"}\n"
"\n");
-
}
}
@@ -690,7 +699,7 @@ void MessageBuilderGenerator::GenerateIsInitialized(
case FieldDescriptor::LABEL_REPEATED:
if (IsMapEntry(field->message_type())) {
printer->Print(
- "for ($type$ item : get$name$().values()) {\n"
+ "for ($type$ item : get$name$Map().values()) {\n"
" if (!item.isInitialized()) {\n"
" return false;\n"
" }\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 14281816..cba18360 100644
--- a/src/google/protobuf/compiler/java/java_message_field_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_field_lite.cc
@@ -145,6 +145,7 @@ GenerateInterfaceMembers(io::Printer* printer) const {
void ImmutableMessageFieldLiteGenerator::
GenerateMembers(io::Printer* printer) const {
+
printer->Print(variables_,
"private $type$ $name$_;\n");
PrintExtraFieldInfo(variables_, printer);
diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/java_message_lite.cc
index 7c8c4a03..0c5a1f8a 100644
--- a/src/google/protobuf/compiler/java/java_message_lite.cc
+++ b/src/google/protobuf/compiler/java/java_message_lite.cc
@@ -179,6 +179,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
MaybePrintGeneratedAnnotation(context_, printer, descriptor_,
/* immutable = */ true);
+
// The builder_type stores the super type name of the nested Builder class.
string builder_type;
if (descriptor_->extension_range_count() > 0) {
@@ -203,7 +204,6 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
}
printer->Indent();
-
GenerateConstructor(printer);
// Nested types
@@ -748,7 +748,7 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
case FieldDescriptor::LABEL_REPEATED:
if (IsMapEntry(field->message_type())) {
printer->Print(
- "for ($type$ item : get$name$().values()) {\n"
+ "for ($type$ item : get$name$Map().values()) {\n"
" if (!item.isInitialized()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
diff --git a/src/google/protobuf/compiler/java/java_service.cc b/src/google/protobuf/compiler/java/java_service.cc
index 9f34f010..cfa8295d 100644
--- a/src/google/protobuf/compiler/java/java_service.cc
+++ b/src/google/protobuf/compiler/java/java_service.cc
@@ -184,6 +184,10 @@ void ImmutableServiceGenerator::GenerateAbstractMethods(io::Printer* printer) {
}
}
+string ImmutableServiceGenerator::GetOutput(const MethodDescriptor* method) {
+ return name_resolver_->GetImmutableClassName(method->output_type());
+}
+
void ImmutableServiceGenerator::GenerateCallMethod(io::Printer* printer) {
printer->Print(
"\n"
@@ -209,8 +213,7 @@ void ImmutableServiceGenerator::GenerateCallMethod(io::Printer* printer) {
vars["method"] = UnderscoresToCamelCase(method);
vars["input"] = name_resolver_->GetImmutableClassName(
method->input_type());
- vars["output"] = name_resolver_->GetImmutableClassName(
- method->output_type());
+ vars["output"] = GetOutput(method);
printer->Print(vars,
"case $index$:\n"
" this.$method$(controller, ($input$)request,\n"
@@ -257,8 +260,7 @@ void ImmutableServiceGenerator::GenerateCallBlockingMethod(
vars["method"] = UnderscoresToCamelCase(method);
vars["input"] = name_resolver_->GetImmutableClassName(
method->input_type());
- vars["output"] = name_resolver_->GetImmutableClassName(
- method->output_type());
+ vars["output"] = GetOutput(method);
printer->Print(vars,
"case $index$:\n"
" return impl.$method$(controller, ($input$)request);\n");
@@ -353,8 +355,7 @@ void ImmutableServiceGenerator::GenerateStub(io::Printer* printer) {
map<string, string> vars;
vars["index"] = SimpleItoa(i);
- vars["output"] = name_resolver_->GetImmutableClassName(
- method->output_type());
+ vars["output"] = GetOutput(method);
printer->Print(vars,
"channel.callMethod(\n"
" getDescriptor().getMethods().get($index$),\n"
@@ -418,8 +419,7 @@ void ImmutableServiceGenerator::GenerateBlockingStub(io::Printer* printer) {
map<string, string> vars;
vars["index"] = SimpleItoa(i);
- vars["output"] = name_resolver_->GetImmutableClassName(
- method->output_type());
+ vars["output"] = GetOutput(method);
printer->Print(vars,
"return ($output$) channel.callBlockingMethod(\n"
" getDescriptor().getMethods().get($index$),\n"
@@ -443,7 +443,7 @@ void ImmutableServiceGenerator::GenerateMethodSignature(io::Printer* printer,
map<string, string> vars;
vars["name"] = UnderscoresToCamelCase(method);
vars["input"] = name_resolver_->GetImmutableClassName(method->input_type());
- vars["output"] = name_resolver_->GetImmutableClassName(method->output_type());
+ vars["output"] = GetOutput(method);
vars["abstract"] = (is_abstract == IS_ABSTRACT) ? "abstract" : "";
printer->Print(vars,
"public $abstract$ void $name$(\n"
@@ -458,7 +458,7 @@ void ImmutableServiceGenerator::GenerateBlockingMethodSignature(
map<string, string> vars;
vars["method"] = UnderscoresToCamelCase(method);
vars["input"] = name_resolver_->GetImmutableClassName(method->input_type());
- vars["output"] = name_resolver_->GetImmutableClassName(method->output_type());
+ vars["output"] = GetOutput(method);
printer->Print(vars,
"\n"
"public $output$ $method$(\n"
diff --git a/src/google/protobuf/compiler/java/java_service.h b/src/google/protobuf/compiler/java/java_service.h
index 5fc9e2f6..12b3f942 100644
--- a/src/google/protobuf/compiler/java/java_service.h
+++ b/src/google/protobuf/compiler/java/java_service.h
@@ -122,6 +122,9 @@ class ImmutableServiceGenerator : public ServiceGenerator {
void GenerateBlockingMethodSignature(io::Printer* printer,
const MethodDescriptor* method);
+ // Return the output type of the method.
+ string GetOutput(const MethodDescriptor* method);
+
Context* context_;
ClassNameResolver* name_resolver_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableServiceGenerator);
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 52893721..18bf1f51 100644
--- a/src/google/protobuf/compiler/java/java_shared_code_generator.cc
+++ b/src/google/protobuf/compiler/java/java_shared_code_generator.cc
@@ -119,7 +119,6 @@ void SharedCodeGenerator::Generate(GeneratorContext* context,
}
}
-
void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
// Embed the descriptor. We simply serialize the entire FileDescriptorProto
// and embed it as a string literal, which is parsed and built into real
@@ -134,7 +133,6 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
FileDescriptorProto file_proto;
file_->CopyTo(&file_proto);
-
string file_data;
file_proto.SerializeToString(&file_data);
diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc
index 58c77d00..47ecc537 100755
--- a/src/google/protobuf/compiler/js/js_generator.cc
+++ b/src/google/protobuf/compiler/js/js_generator.cc
@@ -28,7 +28,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#include "google/protobuf/compiler/js/js_generator.h"
+#include <google/protobuf/compiler/js/js_generator.h>
#include <assert.h>
#include <algorithm>
@@ -153,8 +153,8 @@ string StripProto(const string& filename) {
// Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript
// file foo/bar/baz.js.
-string GetJSFilename(const string& filename) {
- return StripProto(filename) + "_pb.js";
+string GetJSFilename(const GeneratorOptions& options, const string& filename) {
+ return StripProto(filename) + options.GetFileNameExtension();
}
// Given a filename like foo/bar/baz.proto, returns the root directory
@@ -208,28 +208,28 @@ string GetPath(const GeneratorOptions& options,
}
}
-// Forward declare, so that GetPrefix can call this method,
-// which in turn, calls GetPrefix.
-string GetPath(const GeneratorOptions& options,
- const Descriptor* descriptor);
+// Returns the name of the message with a leading dot and taking into account
+// nesting, for example ".OuterMessage.InnerMessage", or returns empty if
+// descriptor is null. This function does not handle namespacing, only message
+// nesting.
+string GetNestedMessageName(const Descriptor* descriptor) {
+ if (descriptor == NULL) {
+ return "";
+ }
+ return StripPrefixString(descriptor->full_name(),
+ descriptor->file()->package());
+}
// Returns the path prefix for a message or enumeration that
// lives under the given file and containing type.
string GetPrefix(const GeneratorOptions& options,
const FileDescriptor* file_descriptor,
const Descriptor* containing_type) {
- string prefix = "";
-
- if (containing_type == NULL) {
- prefix = GetPath(options, file_descriptor);
- } else {
- prefix = GetPath(options, containing_type);
- }
-
+ string prefix = GetPath(options, file_descriptor) +
+ GetNestedMessageName(containing_type);
if (!prefix.empty()) {
prefix += ".";
}
-
return prefix;
}
@@ -273,11 +273,13 @@ string GetPath(const GeneratorOptions& options,
string MaybeCrossFileRef(const GeneratorOptions& options,
const FileDescriptor* from_file,
const Descriptor* to_message) {
- if (options.import_style == GeneratorOptions::IMPORT_COMMONJS &&
+ if (options.import_style == GeneratorOptions::kImportCommonJs &&
from_file != to_message->file()) {
// Cross-file ref in CommonJS needs to use the module alias instead of
// the global name.
- return ModuleAlias(to_message->file()->name()) + "." + to_message->name();
+ return ModuleAlias(to_message->file()->name()) +
+ GetNestedMessageName(to_message->containing_type()) +
+ "." + to_message->name();
} else {
// Within a single file we use a full name.
return GetPath(options, to_message);
@@ -405,21 +407,24 @@ string ToFileName(const string& input) {
// that top-level extensions should go in.
string GetExtensionFileName(const GeneratorOptions& options,
const FileDescriptor* file) {
- return options.output_dir + "/" + ToFileName(GetPath(options, file)) + ".js";
+ return options.output_dir + "/" + ToFileName(GetPath(options, file)) +
+ options.GetFileNameExtension();
}
// When we're generating one output file per type name, this is the filename
// that a top-level message should go in.
string GetMessageFileName(const GeneratorOptions& options,
const Descriptor* desc) {
- return options.output_dir + "/" + ToFileName(desc->name()) + ".js";
+ return options.output_dir + "/" + ToFileName(desc->name()) +
+ options.GetFileNameExtension();
}
// When we're generating one output file per type name, this is the filename
// that a top-level message should go in.
string GetEnumFileName(const GeneratorOptions& options,
const EnumDescriptor* desc) {
- return options.output_dir + "/" + ToFileName(desc->name()) + ".js";
+ return options.output_dir + "/" + ToFileName(desc->name()) +
+ options.GetFileNameExtension();
}
// Returns the message/response ID, if set.
@@ -444,9 +449,19 @@ bool IgnoreField(const FieldDescriptor* field) {
}
+// Used inside Google only -- do not remove.
+bool ShouldTreatMapsAsRepeatedFields(const FileDescriptor& descriptor) {
+ return false;
+}
+
// Do we ignore this message type?
bool IgnoreMessage(const GeneratorOptions& options, const Descriptor* d) {
- return d->options().map_entry();
+ return d->options().map_entry() &&
+ !ShouldTreatMapsAsRepeatedFields(*d->file());
+}
+
+bool IsMap(const GeneratorOptions& options, const FieldDescriptor* field) {
+ return field->is_map() && !ShouldTreatMapsAsRepeatedFields(*field->file());
}
// Does JSPB ignore this entire oneof? True only if all fields are ignored.
@@ -459,10 +474,8 @@ bool IgnoreOneof(const OneofDescriptor* oneof) {
return true;
}
-string JSIdent(const GeneratorOptions& options,
- const FieldDescriptor* field,
- bool is_upper_camel,
- bool is_map) {
+string JSIdent(const GeneratorOptions& options, const FieldDescriptor* field,
+ bool is_upper_camel, bool is_map, bool drop_list) {
string result;
if (field->type() == FieldDescriptor::TYPE_GROUP) {
result = is_upper_camel ?
@@ -473,10 +486,10 @@ string JSIdent(const GeneratorOptions& options,
ToUpperCamel(ParseLowerUnderscore(field->name())) :
ToLowerCamel(ParseLowerUnderscore(field->name()));
}
- if (is_map || (field->is_map())) {
+ if (is_map || IsMap(options, field)) {
// JSPB-style or proto3-style map.
result += "Map";
- } else if (field->is_repeated()) {
+ } else if (!drop_list && field->is_repeated()) {
// Repeated field.
result += "List";
}
@@ -485,11 +498,10 @@ string JSIdent(const GeneratorOptions& options,
string JSObjectFieldName(const GeneratorOptions& options,
const FieldDescriptor* field) {
- string name = JSIdent(
- options,
- field,
- /* is_upper_camel = */ false,
- /* is_map = */ false);
+ string name = JSIdent(options, field,
+ /* is_upper_camel = */ false,
+ /* is_map = */ false,
+ /* drop_list = */ false);
if (IsReserved(name)) {
name = "pb_" + name;
}
@@ -514,10 +526,11 @@ string JSByteGetterSuffix(BytesMode bytes_mode) {
// name, e.g. MyField for .getMyField().
string JSGetterName(const GeneratorOptions& options,
const FieldDescriptor* field,
- BytesMode bytes_mode = BYTES_DEFAULT) {
+ BytesMode bytes_mode = BYTES_DEFAULT,
+ bool drop_list = false) {
string name = JSIdent(options, field,
/* is_upper_camel = */ true,
- /* is_map = */ false);
+ /* is_map = */ false, drop_list);
if (field->type() == FieldDescriptor::TYPE_BYTES) {
string suffix = JSByteGetterSuffix(bytes_mode);
if (!suffix.empty()) {
@@ -535,7 +548,8 @@ string JSMapGetterName(const GeneratorOptions& options,
const FieldDescriptor* field) {
return JSIdent(options, field,
/* is_upper_camel = */ true,
- /* is_map = */ true);
+ /* is_map = */ true,
+ /* drop_list = */ false);
}
@@ -768,6 +782,10 @@ string MaybeNumberString(const FieldDescriptor* field, const string& orig) {
}
string JSFieldDefault(const FieldDescriptor* field) {
+ if (field->is_repeated()) {
+ return "[]";
+ }
+
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_INT32:
return MaybeNumberString(
@@ -909,20 +927,91 @@ string JSTypeName(const GeneratorOptions& options,
}
}
-bool HasFieldPresence(const FieldDescriptor* field);
+bool UseBrokenPresenceSemantics(const GeneratorOptions& options,
+ const FieldDescriptor* field) {
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
+ return options.broken_proto3_semantics;
+ } else if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO2) {
+ return false;
+ } else {
+ GOOGLE_LOG(FATAL) << "We can only handle syntax=proto2 and syntax=proto3.";
+ return false;
+ }
+}
+
+// Returns true for fields that return "null" from accessors when they are
+// unset. This should normally only be true for non-repeated submessages, but
+// we have legacy users who relied on old behavior where accessors behaved this
+// way.
+bool ReturnsNullWhenUnset(const GeneratorOptions& options,
+ const FieldDescriptor* field) {
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
+ field->is_optional()) {
+ return true;
+ }
+
+ // TODO(haberman): remove this case and unconditionally return false.
+ return UseBrokenPresenceSemantics(options, field) && !field->is_repeated() &&
+ !field->has_default_value();
+}
+
+// In a sane world, this would be the same as ReturnsNullWhenUnset(). But in
+// the status quo, some fields declare that they never return null/undefined
+// even though they actually do:
+// * required fields
+// * optional enum fields
+// * proto3 primitive fields.
+bool DeclaredReturnTypeIsNullable(const GeneratorOptions& options,
+ const FieldDescriptor* field) {
+ if (field->is_required() || field->type() == FieldDescriptor::TYPE_ENUM) {
+ return false;
+ }
+
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 &&
+ field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
+ return false;
+ }
+
+ return ReturnsNullWhenUnset(options, field);
+}
+
+bool SetterAcceptsUndefined(const GeneratorOptions& options,
+ const FieldDescriptor* field) {
+ if (ReturnsNullWhenUnset(options, field)) {
+ return true;
+ }
+
+ // Broken presence semantics always accepts undefined for setters.
+ return UseBrokenPresenceSemantics(options, field);
+}
+
+bool SetterAcceptsNull(const GeneratorOptions& options,
+ const FieldDescriptor* field) {
+ if (ReturnsNullWhenUnset(options, field)) {
+ return true;
+ }
+
+ // With broken presence semantics, fields with defaults accept "null" for
+ // setters, but other fields do not. This is a strange quirk of the old
+ // codegen.
+ return UseBrokenPresenceSemantics(options, field) &&
+ field->has_default_value();
+}
+
+// Returns types which are known to by non-nullable by default.
+// The style guide requires that we omit "!" in this case.
+bool IsPrimitive(const string& type) {
+ return type == "undefined" || type == "string" || type == "number" ||
+ type == "boolean";
+}
string JSFieldTypeAnnotation(const GeneratorOptions& options,
const FieldDescriptor* field,
- bool force_optional,
+ bool is_setter_argument,
bool force_present,
bool singular_if_not_packed,
BytesMode bytes_mode = BYTES_DEFAULT) {
- bool is_primitive =
- (field->cpp_type() != FieldDescriptor::CPPTYPE_ENUM &&
- field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE &&
- (field->type() != FieldDescriptor::TYPE_BYTES ||
- bytes_mode == BYTES_B64));
-
+ GOOGLE_CHECK(!(is_setter_argument && force_present));
string jstype = JSTypeName(options, field, bytes_mode);
if (field->is_repeated() &&
@@ -931,27 +1020,35 @@ string JSFieldTypeAnnotation(const GeneratorOptions& options,
bytes_mode == BYTES_DEFAULT) {
jstype = "(Array<!Uint8Array>|Array<string>)";
} else {
- if (!is_primitive) {
+ if (!IsPrimitive(jstype)) {
jstype = "!" + jstype;
}
jstype = "Array.<" + jstype + ">";
}
- if (!force_optional) {
- jstype = "!" + jstype;
- }
}
- if (field->is_optional() && is_primitive &&
- force_optional && !force_present) {
- jstype += "?";
- } else if (field->is_required() && !is_primitive && !force_optional) {
- jstype = "!" + jstype;
- }
+ bool is_null_or_undefined = false;
+
+ if (is_setter_argument) {
+ if (SetterAcceptsNull(options, field)) {
+ jstype = "?" + jstype;
+ is_null_or_undefined = true;
+ }
- if (force_optional && HasFieldPresence(field)) {
- jstype += "|undefined";
+ if (SetterAcceptsUndefined(options, field)) {
+ jstype += "|undefined";
+ is_null_or_undefined = true;
+ }
+ } else if (force_present) {
+ // Don't add null or undefined.
+ } else {
+ if (DeclaredReturnTypeIsNullable(options, field)) {
+ jstype = "?" + jstype;
+ is_null_or_undefined = true;
+ }
}
- if (force_present && jstype[0] != '!' && !is_primitive) {
+
+ if (!is_null_or_undefined && !IsPrimitive(jstype)) {
jstype = "!" + jstype;
}
@@ -1007,9 +1104,10 @@ string JSReturnDoc(const GeneratorOptions& options,
return "";
}
-bool HasRepeatedFields(const Descriptor* desc) {
+bool HasRepeatedFields(const GeneratorOptions& options,
+ const Descriptor* desc) {
for (int i = 0; i < desc->field_count(); i++) {
- if (desc->field(i)->is_repeated() && !desc->field(i)->is_map()) {
+ if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) {
return true;
}
}
@@ -1020,8 +1118,9 @@ static const char* kRepeatedFieldArrayName = ".repeatedFields_";
string RepeatedFieldsArrayName(const GeneratorOptions& options,
const Descriptor* desc) {
- return HasRepeatedFields(desc) ?
- (GetPath(options, desc) + kRepeatedFieldArrayName) : "null";
+ return HasRepeatedFields(options, desc)
+ ? (GetPath(options, desc) + kRepeatedFieldArrayName)
+ : "null";
}
bool HasOneofFields(const Descriptor* desc) {
@@ -1041,10 +1140,11 @@ string OneofFieldsArrayName(const GeneratorOptions& options,
(GetPath(options, desc) + kOneofGroupArrayName) : "null";
}
-string RepeatedFieldNumberList(const Descriptor* desc) {
+string RepeatedFieldNumberList(const GeneratorOptions& options,
+ const Descriptor* desc) {
std::vector<string> numbers;
for (int i = 0; i < desc->field_count(); i++) {
- if (desc->field(i)->is_repeated() && !desc->field(i)->is_map()) {
+ if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) {
numbers.push_back(JSFieldIndex(desc->field(i)));
}
}
@@ -1108,7 +1208,7 @@ string JSExtensionsObjectName(const GeneratorOptions& options,
const FileDescriptor* from_file,
const Descriptor* desc) {
if (desc->full_name() == "google.protobuf.bridge.MessageSet") {
- // TODO(haberman): fix this for the IMPORT_COMMONJS case.
+ // TODO(haberman): fix this for the kImportCommonJs case.
return "jspb.Message.messageSetExtensions";
} else {
return MaybeCrossFileRef(options, from_file, desc) + ".extensions";
@@ -1130,7 +1230,7 @@ const FieldDescriptor* MapFieldValue(const FieldDescriptor* field) {
string FieldDefinition(const GeneratorOptions& options,
const FieldDescriptor* field) {
- if (field->is_map()) {
+ if (IsMap(options, field)) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
string key_type = ProtoTypeName(options, key_field);
@@ -1254,47 +1354,24 @@ string GetPivot(const Descriptor* desc) {
return SimpleItoa(pivot);
}
-// Returns true for fields that represent "null" as distinct from the default
-// value. See http://go/proto3#heading=h.kozewqqcqhuz for more information.
-bool HasFieldPresence(const FieldDescriptor* field) {
- if (field->is_repeated()) {
+// Whether this field represents presence. For fields with presence, we
+// generate extra methods (clearFoo() and hasFoo()) for this field.
+bool HasFieldPresence(const GeneratorOptions& options,
+ const FieldDescriptor* field) {
+ if (field->is_repeated() || field->is_map()) {
+ // We say repeated fields and maps don't have presence, but we still do
+ // generate clearFoo() methods for them through a special case elsewhere.
return false;
}
- return
- (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ||
- (field->containing_oneof() != NULL) ||
- (field->file()->syntax() != FileDescriptor::SYNTAX_PROTO3);
-}
-
-// For proto3 fields without presence, returns a string representing the default
-// value in JavaScript. See http://go/proto3#heading=h.kozewqqcqhuz for more
-// information.
-string Proto3PrimitiveFieldDefault(const FieldDescriptor* field) {
- switch (field->cpp_type()) {
- case FieldDescriptor::CPPTYPE_INT32:
- case FieldDescriptor::CPPTYPE_INT64:
- case FieldDescriptor::CPPTYPE_UINT32:
- case FieldDescriptor::CPPTYPE_UINT64: {
- return "0";
- }
-
- case FieldDescriptor::CPPTYPE_ENUM:
- case FieldDescriptor::CPPTYPE_FLOAT:
- case FieldDescriptor::CPPTYPE_DOUBLE:
- return "0";
-
- case FieldDescriptor::CPPTYPE_BOOL:
- return "false";
-
- case FieldDescriptor::CPPTYPE_STRING: // includes BYTES
- return "\"\"";
-
- default:
- // MESSAGE is handled separately.
- assert(false);
- return "";
+ if (UseBrokenPresenceSemantics(options, field)) {
+ // Proto3 files with broken presence semantics have field presence.
+ return true;
}
+
+ return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
+ field->containing_oneof() != NULL ||
+ field->file()->syntax() == FileDescriptor::SYNTAX_PROTO2;
}
// We use this to implement the semantics that same file can be generated
@@ -1524,8 +1601,19 @@ void Generator::GenerateProvides(const GeneratorOptions& options,
std::set<string>* provided) const {
for (std::set<string>::iterator it = provided->begin();
it != provided->end(); ++it) {
- printer->Print("goog.provide('$name$');\n",
- "name", *it);
+ if (options.import_style == GeneratorOptions::kImportClosure) {
+ printer->Print("goog.provide('$name$');\n", "name", *it);
+ } else {
+ // We aren't using Closure's import system, but we use goog.exportSymbol()
+ // to construct the expected tree of objects, eg.
+ //
+ // goog.exportSymbol('foo.bar.Baz', null, this);
+ //
+ // // Later generated code expects foo.bar = {} to exist:
+ // foo.bar.Baz = function() { /* ... */ }
+ printer->Print("goog.exportSymbol('$name$', null, global);\n", "name",
+ *it);
+ }
}
}
@@ -1548,7 +1636,7 @@ void Generator::GenerateRequiresForLibrary(
const GeneratorOptions& options, io::Printer* printer,
const vector<const FileDescriptor*>& files,
std::set<string>* provided) const {
- GOOGLE_CHECK_EQ(options.import_style, GeneratorOptions::IMPORT_CLOSURE);
+ GOOGLE_CHECK_EQ(options.import_style, GeneratorOptions::kImportClosure);
// For Closure imports we need to import every message type individually.
std::set<string> required;
std::set<string> forwards;
@@ -1623,6 +1711,10 @@ void Generator::GenerateRequiresImpl(const GeneratorOptions& options,
}
}
if (require_extension) {
+ if (options.binary) {
+ printer->Print(
+ "goog.require('jspb.ExtensionFieldBinaryInfo');\n");
+ }
printer->Print(
"goog.require('jspb.ExtensionFieldInfo');\n");
}
@@ -1755,14 +1847,13 @@ void Generator::GenerateClass(const GeneratorOptions& options,
GenerateClassDeserializeBinary(options, printer, desc);
GenerateClassSerializeBinary(options, printer, desc);
}
- GenerateClassClone(options, printer, desc);
GenerateClassRegistration(options, printer, desc);
GenerateClassFields(options, printer, desc);
if (IsExtendable(desc) && desc->full_name() != "google.protobuf.bridge.MessageSet") {
GenerateClassExtensionFieldInfo(options, printer, desc);
}
- if (options.import_style != GeneratorOptions:: IMPORT_CLOSURE) {
+ if (options.import_style != GeneratorOptions::kImportClosure) {
for (int i = 0; i < desc->extension_count(); i++) {
GenerateExtension(options, printer, desc->extension(i));
}
@@ -1820,7 +1911,7 @@ void Generator::GenerateClassConstructor(const GeneratorOptions& options,
void Generator::GenerateClassFieldInfo(const GeneratorOptions& options,
io::Printer* printer,
const Descriptor* desc) const {
- if (HasRepeatedFields(desc)) {
+ if (HasRepeatedFields(options, desc)) {
printer->Print(
"/**\n"
" * List of repeated fields within this message type.\n"
@@ -1831,7 +1922,7 @@ void Generator::GenerateClassFieldInfo(const GeneratorOptions& options,
"\n",
"classname", GetPath(options, desc),
"rptfieldarray", kRepeatedFieldArrayName,
- "rptfields", RepeatedFieldNumberList(desc));
+ "rptfields", RepeatedFieldNumberList(options, desc));
}
if (HasOneofFields(desc)) {
@@ -2000,14 +2091,59 @@ void Generator::GenerateClassToObject(const GeneratorOptions& options,
"classname", GetPath(options, desc));
}
+void Generator::GenerateFieldValueExpression(io::Printer* printer,
+ const char *obj_reference,
+ const FieldDescriptor* field,
+ bool use_default) const {
+ bool is_float_or_double =
+ field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT ||
+ field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE;
+ if (use_default) {
+ if (is_float_or_double) {
+ // Coerce "Nan" and "Infinity" to actual float values.
+ //
+ // This will change null to 0, but that doesn't matter since we're getting
+ // with a default.
+ printer->Print("+");
+ }
+
+ printer->Print(
+ "jspb.Message.getFieldWithDefault($obj$, $index$, $default$)",
+ "obj", obj_reference,
+ "index", JSFieldIndex(field),
+ "default", JSFieldDefault(field));
+ } else {
+ if (is_float_or_double) {
+ if (field->is_required()) {
+ // Use "+" to convert all fields to numeric (including null).
+ printer->Print(
+ "+jspb.Message.getField($obj$, $index$)",
+ "index", JSFieldIndex(field),
+ "obj", obj_reference);
+ } else {
+ // Converts "NaN" and "Infinity" while preserving null.
+ printer->Print(
+ "jspb.Message.get$cardinality$FloatingPointField($obj$, $index$)",
+ "cardinality", field->is_repeated() ? "Repeated" : "Optional",
+ "index", JSFieldIndex(field),
+ "obj", obj_reference);
+ }
+ } else {
+ printer->Print("jspb.Message.getField($obj$, $index$)",
+ "index", JSFieldIndex(field),
+ "obj", obj_reference);
+ }
+ }
+}
+
void Generator::GenerateClassFieldToObject(const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
printer->Print("$fieldname$: ",
"fieldname", JSObjectFieldName(options, field));
- if (field->is_map()) {
- printer->Print("(f = msg.get$name$(true)) ? f.toArray() : []",
+ if (IsMap(options, field)) {
+ printer->Print("(f = msg.get$name$()) ? f.toArray() : []",
"name", JSGetterName(options, field));
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
// Message field.
@@ -2024,40 +2160,29 @@ void Generator::GenerateClassFieldToObject(const GeneratorOptions& options,
"getter", JSGetterName(options, field),
"type", SubmessageTypeRef(options, field));
}
+ } else if (field->type() == FieldDescriptor::TYPE_BYTES) {
+ // For bytes fields we want to always return the B64 data.
+ printer->Print("msg.get$getter$()",
+ "getter", JSGetterName(options, field, BYTES_B64));
} else {
- // Simple field (singular or repeated).
- if ((!HasFieldPresence(field) && !field->is_repeated()) ||
- field->type() == FieldDescriptor::TYPE_BYTES) {
- // Delegate to the generated get<field>() method in order not to duplicate
- // the proto3-field-default-value or byte-coercion logic here.
- printer->Print("msg.get$getter$()",
- "getter", JSGetterName(options, field, BYTES_B64));
- } else {
- if (field->has_default_value()) {
- printer->Print("!msg.has$name$() ? $defaultValue$ : ",
- "name", JSGetterName(options, field),
- "defaultValue", JSFieldDefault(field));
- }
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT ||
- field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE) {
- if (field->is_repeated()) {
- printer->Print("jspb.Message.getRepeatedFloatingPointField("
- "msg, $index$)",
- "index", JSFieldIndex(field));
- } else if (field->is_optional() && !field->has_default_value()) {
- printer->Print("jspb.Message.getOptionalFloatingPointField("
- "msg, $index$)",
- "index", JSFieldIndex(field));
- } else {
- // Convert "NaN" to NaN.
- printer->Print("+jspb.Message.getField(msg, $index$)",
- "index", JSFieldIndex(field));
- }
- } else {
- printer->Print("jspb.Message.getField(msg, $index$)",
- "index", JSFieldIndex(field));
- }
+ bool use_default = field->has_default_value();
+
+ if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 &&
+ // Repeated fields get initialized to their default in the constructor
+ // (why?), so we emit a plain getField() call for them.
+ !field->is_repeated() && !UseBrokenPresenceSemantics(options, field)) {
+ // Proto3 puts all defaults (including implicit defaults) in toObject().
+ // But for proto2 we leave the existing semantics unchanged: unset fields
+ // without default are unset.
+ use_default = true;
}
+
+ // We don't implement this by calling the accessors, because the semantics
+ // of the accessors are changing independently of the toObject() semantics.
+ // We are migrating the accessors to return defaults instead of null, but
+ // it may take longer to migrate toObject (or we might not want to do it at
+ // all). So we want to generate independent code.
+ GenerateFieldValueExpression(printer, "msg", field, use_default);
}
}
@@ -2091,8 +2216,7 @@ void Generator::GenerateClassFieldFromObject(
const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
-
- if (field->is_map()) {
+ if (IsMap(options, field)) {
// `msg` is a newly-constructed message object that has not yet built any
// map containers wrapping underlying arrays, so we can simply directly set
// the array here without fear of a stale wrapper.
@@ -2133,21 +2257,6 @@ void Generator::GenerateClassFieldFromObject(
}
}
-void Generator::GenerateClassClone(const GeneratorOptions& options,
- io::Printer* printer,
- const Descriptor* desc) const {
- printer->Print(
- "/**\n"
- " * Creates a deep clone of this proto. No data is shared with the "
- "original.\n"
- " * @return {!$name$} The clone.\n"
- " */\n"
- "$name$.prototype.cloneMessage = function() {\n"
- " return /** @type {!$name$} */ (jspb.Message.cloneMessage(this));\n"
- "};\n\n\n",
- "name", GetPath(options, desc));
-}
-
void Generator::GenerateClassRegistration(const GeneratorOptions& options,
io::Printer* printer,
const Descriptor* desc) const {
@@ -2175,12 +2284,11 @@ void GenerateBytesWrapper(const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field,
BytesMode bytes_mode) {
- string type =
- JSFieldTypeAnnotation(options, field,
- /* force_optional = */ false,
- /* force_present = */ !HasFieldPresence(field),
- /* singular_if_not_packed = */ false,
- bytes_mode);
+ string type = JSFieldTypeAnnotation(
+ options, field,
+ /* is_setter_argument = */ false,
+ /* force_present = */ false,
+ /* singular_if_not_packed = */ false, bytes_mode);
printer->Print(
"/**\n"
" * $fielddef$\n"
@@ -2208,20 +2316,20 @@ void GenerateBytesWrapper(const GeneratorOptions& options,
void Generator::GenerateClassField(const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
- if (field->is_map()) {
+ if (IsMap(options, field)) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
// Map field: special handling to instantiate the map object on demand.
string key_type =
JSFieldTypeAnnotation(
options, key_field,
- /* force_optional = */ false,
+ /* is_setter_argument = */ false,
/* force_present = */ true,
/* singular_if_not_packed = */ false);
string value_type =
JSFieldTypeAnnotation(
options, value_field,
- /* force_optional = */ false,
+ /* is_setter_argument = */ false,
/* force_present = */ true,
/* singular_if_not_packed = */ false);
@@ -2275,7 +2383,7 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
"fielddef", FieldDefinition(options, field),
"comment", FieldComments(field, BYTES_DEFAULT),
"type", JSFieldTypeAnnotation(options, field,
- /* force_optional = */ false,
+ /* is_setter_argument = */ false,
/* force_present = */ false,
/* singular_if_not_packed = */ false));
printer->Print(
@@ -2289,7 +2397,7 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
"class", GetPath(options, field->containing_type()),
"name", JSGetterName(options, field),
"type", JSFieldTypeAnnotation(options, field,
- /* force_optional = */ false,
+ /* is_setter_argument = */ false,
/* force_present = */ false,
/* singular_if_not_packed = */ false),
"rpt", (field->is_repeated() ? "Repeated" : ""),
@@ -2298,12 +2406,12 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
"required", (field->label() == FieldDescriptor::LABEL_REQUIRED ?
", 1" : ""));
printer->Print(
- "/** @param {$optionaltype$} value $returndoc$ */\n"
+ "/** @param {$optionaltype$} value$returndoc$ */\n"
"$class$.prototype.set$name$ = function(value) {\n"
" jspb.Message.set$oneoftag$$repeatedtag$WrapperField(",
"optionaltype",
JSFieldTypeAnnotation(options, field,
- /* force_optional = */ true,
+ /* is_setter_argument = */ true,
/* force_present = */ false,
/* singular_if_not_packed = */ false),
"returndoc", JSReturnDoc(options, field),
@@ -2322,16 +2430,9 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
(", " + JSOneofArray(options, field)) : ""),
"returnvalue", JSReturnClause(field));
- printer->Print(
- "$class$.prototype.clear$name$ = function() {\n"
- " this.set$name$($clearedvalue$);$returnvalue$\n"
- "};\n"
- "\n"
- "\n",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
- "clearedvalue", (field->is_repeated() ? "[]" : "undefined"),
- "returnvalue", JSReturnClause(field));
+ if (field->is_repeated()) {
+ GenerateRepeatedMessageHelperMethods(options, printer, field);
+ }
} else {
bool untyped =
@@ -2345,12 +2446,12 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
BytesMode bytes_mode =
field->type() == FieldDescriptor::TYPE_BYTES && !options.binary ?
BYTES_B64 : BYTES_DEFAULT;
- string typed_annotation =
- JSFieldTypeAnnotation(options, field,
- /* force_optional = */ false,
- /* force_present = */ !HasFieldPresence(field),
- /* singular_if_not_packed = */ false,
- /* bytes_mode = */ bytes_mode);
+ string typed_annotation = JSFieldTypeAnnotation(
+ options, field,
+ /* is_setter_argument = */ false,
+ /* force_present = */ false,
+ /* singular_if_not_packed = */ false,
+ /* bytes_mode = */ bytes_mode);
if (untyped) {
printer->Print(
"/**\n"
@@ -2382,36 +2483,21 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
"type", typed_annotation);
}
- // For proto3 fields without presence, use special getters that will return
- // defaults when the field is unset, possibly constructing a value if
- // required.
- if (!HasFieldPresence(field) && !field->is_repeated()) {
- printer->Print("jspb.Message.getFieldProto3(this, $index$, $default$)",
- "index", JSFieldIndex(field),
- "default", Proto3PrimitiveFieldDefault(field));
- } else {
- if (!field->is_repeated()) {
- printer->Print("!this.has$name$() ? $defaultValue$ : ",
- "name", JSGetterName(options, field),
- "defaultValue", JSFieldDefault(field));
- }
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT ||
- field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE) {
- if (field->is_repeated()) {
- printer->Print("jspb.Message.getRepeatedFloatingPointField("
- "this, $index$)",
- "index", JSFieldIndex(field));
- } else {
- // Convert "NaN" to NaN.
- printer->Print("+jspb.Message.getField(this, $index$)",
- "index", JSFieldIndex(field));
- }
- } else {
- printer->Print("jspb.Message.getField(this, $index$)",
- "index", JSFieldIndex(field));
- }
+ bool use_default = !ReturnsNullWhenUnset(options, field);
+
+ // Raw fields with no default set should just return undefined.
+ if (untyped && !field->has_default_value()) {
+ use_default = false;
+ }
+
+ // Repeated fields get initialized to their default in the constructor
+ // (why?), so we emit a plain getField() call for them.
+ if (field->is_repeated()) {
+ use_default = false;
}
+ GenerateFieldValueExpression(printer, "this", field, use_default);
+
if (untyped) {
printer->Print(
";\n"
@@ -2434,17 +2520,17 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
if (untyped) {
printer->Print(
"/**\n"
- " * @param {*} value $returndoc$\n"
+ " * @param {*} value$returndoc$\n"
" */\n",
"returndoc", JSReturnDoc(options, field));
} else {
printer->Print(
- "/** @param {$optionaltype$} value $returndoc$ */\n",
- "optionaltype",
- JSFieldTypeAnnotation(options, field,
- /* force_optional = */ true,
- /* force_present = */ !HasFieldPresence(field),
- /* singular_if_not_packed = */ false),
+ "/** @param {$optionaltype$} value$returndoc$ */\n", "optionaltype",
+ JSFieldTypeAnnotation(
+ options, field,
+ /* is_setter_argument = */ true,
+ /* force_present = */ false,
+ /* singular_if_not_packed = */ false),
"returndoc", JSReturnDoc(options, field));
}
printer->Print(
@@ -2471,36 +2557,70 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
if (untyped) {
printer->Print(
"/**\n"
- " * Clears the value. $returndoc$\n"
+ " * Clears the value.$returndoc$\n"
" */\n",
"returndoc", JSReturnDoc(options, field));
}
- if (HasFieldPresence(field) || field->is_repeated()) {
- printer->Print(
- "$class$.prototype.clear$name$ = function() {\n"
- " jspb.Message.set$oneoftag$Field(this, $index$$oneofgroup$, ",
- "class", GetPath(options, field->containing_type()),
- "name", JSGetterName(options, field),
- "oneoftag", (field->containing_oneof() ? "Oneof" : ""),
- "oneofgroup", (field->containing_oneof() ?
- (", " + JSOneofArray(options, field)) : ""),
- "index", JSFieldIndex(field));
- printer->Print(
- "$clearedvalue$);$returnvalue$\n"
- "};\n"
- "\n"
- "\n",
- "clearedvalue", (field->is_repeated() ? "[]" : "undefined"),
- "returnvalue", JSReturnClause(field));
+
+ if (field->is_repeated()) {
+ GenerateRepeatedPrimitiveHelperMethods(options, printer, field, untyped);
}
}
- if (HasFieldPresence(field)) {
+ // Generate clearFoo() method for map fields, repeated fields, and other
+ // fields with presence.
+ if (IsMap(options, field)) {
+ printer->Print(
+ "$class$.prototype.clear$name$ = function() {\n"
+ " this.get$name$().clear();$returnvalue$\n"
+ "};\n"
+ "\n"
+ "\n",
+ "class", GetPath(options, field->containing_type()),
+ "name", JSGetterName(options, field),
+ "returnvalue", JSReturnClause(field));
+ } else if (field->is_repeated() ||
+ (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
+ !field->is_required())) {
+ // Fields where we can delegate to the regular setter.
+ printer->Print(
+ "$class$.prototype.clear$name$ = function() {\n"
+ " this.set$name$($clearedvalue$);$returnvalue$\n"
+ "};\n"
+ "\n"
+ "\n",
+ "class", GetPath(options, field->containing_type()),
+ "name", JSGetterName(options, field),
+ "clearedvalue", (field->is_repeated() ? "[]" : "undefined"),
+ "returnvalue", JSReturnClause(field));
+ } else if (HasFieldPresence(options, field)) {
+ // Fields where we can't delegate to the regular setter because it doesn't
+ // accept "undefined" as an argument.
+ printer->Print(
+ "$class$.prototype.clear$name$ = function() {\n"
+ " jspb.Message.set$maybeoneof$Field(this, "
+ "$index$$maybeoneofgroup$, ",
+ "class", GetPath(options, field->containing_type()),
+ "name", JSGetterName(options, field),
+ "maybeoneof", (field->containing_oneof() ? "Oneof" : ""),
+ "maybeoneofgroup", (field->containing_oneof() ?
+ (", " + JSOneofArray(options, field)) : ""),
+ "index", JSFieldIndex(field));
+ printer->Print(
+ "$clearedvalue$);$returnvalue$\n"
+ "};\n"
+ "\n"
+ "\n",
+ "clearedvalue", (field->is_repeated() ? "[]" : "undefined"),
+ "returnvalue", JSReturnClause(field));
+ }
+
+ if (HasFieldPresence(options, field)) {
printer->Print(
"/**\n"
" * Returns whether this field is set.\n"
- " * @return{!boolean}\n"
+ " * @return {!boolean}\n"
" */\n"
"$class$.prototype.has$name$ = function() {\n"
" return jspb.Message.getField(this, $index$) != null;\n"
@@ -2513,6 +2633,59 @@ void Generator::GenerateClassField(const GeneratorOptions& options,
}
}
+void Generator::GenerateRepeatedPrimitiveHelperMethods(
+ const GeneratorOptions& options, io::Printer* printer,
+ const FieldDescriptor* field, bool untyped) const {
+ printer->Print(
+ "/**\n"
+ " * @param {!$optionaltype$} value\n"
+ " * @param {number=} opt_index\n"
+ " */\n"
+ "$class$.prototype.add$name$ = function(value, opt_index) {\n"
+ " jspb.Message.addToRepeatedField(this, $index$",
+ "class", GetPath(options, field->containing_type()), "name",
+ JSGetterName(options, field, BYTES_DEFAULT,
+ /* drop_list = */ true),
+ "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "index",
+ JSFieldIndex(field));
+ printer->Print(
+ "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, opt_index);\n"
+ "};\n"
+ "\n"
+ "\n",
+ "type", untyped ? "/** @type{string|number|boolean|!Uint8Array} */(" : "",
+ "typeclose", untyped ? ")" : "", "oneofgroup",
+ (field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""),
+ "rptvalueinit", "");
+}
+
+void Generator::GenerateRepeatedMessageHelperMethods(
+ const GeneratorOptions& options, io::Printer* printer,
+ const FieldDescriptor* field) const {
+ printer->Print(
+ "/**\n"
+ " * @param {!$optionaltype$=} opt_value\n"
+ " * @param {number=} opt_index\n"
+ " * @return {!$optionaltype$}\n"
+ " */\n"
+ "$class$.prototype.add$name$ = function(opt_value, opt_index) {\n"
+ " return jspb.Message.addTo$repeatedtag$WrapperField(",
+ "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), "class",
+ GetPath(options, field->containing_type()), "name",
+ JSGetterName(options, field, BYTES_DEFAULT,
+ /* drop_list = */ true),
+ "repeatedtag", (field->is_repeated() ? "Repeated" : ""));
+
+ printer->Print(
+ "this, $index$$oneofgroup$, opt_value, $ctor$, opt_index);\n"
+ "};\n"
+ "\n"
+ "\n",
+ "index", JSFieldIndex(field), "oneofgroup",
+ (field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""),
+ "ctor", GetPath(options, field->message_type()));
+}
+
void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options,
io::Printer* printer,
const Descriptor* desc) const {
@@ -2554,7 +2727,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.ExtensionFieldBinaryInfo>}\n"
" */\n"
"$class$.extensionsBinary = {};\n"
"\n",
@@ -2636,7 +2809,7 @@ void Generator::GenerateClassDeserializeBinaryField(
printer->Print(" case $num$:\n",
"num", SimpleItoa(field->number()));
- if (field->is_map()) {
+ if (IsMap(options, field)) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
printer->Print(
@@ -2679,13 +2852,9 @@ void Generator::GenerateClassDeserializeBinaryField(
}
if (field->is_repeated() && !field->is_packed()) {
- // Repeated fields receive a |value| one at at a time; append to array
- // returned by get$name$(). Annoyingly, we have to call 'set' after
- // changing the array.
- printer->Print(" msg.get$name$().push(value);\n", "name",
- JSGetterName(options, field));
- printer->Print(" msg.set$name$(msg.get$name$());\n", "name",
- JSGetterName(options, field));
+ printer->Print(
+ " msg.add$name$(value);\n", "name",
+ JSGetterName(options, field, BYTES_DEFAULT, /* drop_list = */ true));
} else {
// Singular fields, and packed repeated fields, receive a |value| either
// as the field's value or as the array of all the field's values; set
@@ -2757,11 +2926,18 @@ void Generator::GenerateClassSerializeBinaryField(
const GeneratorOptions& options,
io::Printer* printer,
const FieldDescriptor* field) const {
- if (HasFieldPresence(field) &&
+ if (HasFieldPresence(options, field) &&
field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
+ string typed_annotation = JSFieldTypeAnnotation(
+ options, field,
+ /* is_setter_argument = */ false,
+ /* force_present = */ false,
+ /* singular_if_not_packed = */ false,
+ /* bytes_mode = */ BYTES_DEFAULT);
printer->Print(
- " f = jspb.Message.getField(this, $index$);\n",
- "index", JSFieldIndex(field));
+ " f = /** @type {$type$} */ (jspb.Message.getField(this, $index$));\n",
+ "index", JSFieldIndex(field),
+ "type", typed_annotation);
} else {
printer->Print(
" f = this.get$name$($nolazy$);\n",
@@ -2770,17 +2946,16 @@ void Generator::GenerateClassSerializeBinaryField(
"nolazy", (field->is_map()) ? "true" : "");
}
-
// Print an `if (condition)` statement that evaluates to true if the field
// goes on the wire.
- if (field->is_map()) {
+ if (IsMap(options, field)) {
printer->Print(
" if (f && f.getLength() > 0) {\n");
} else if (field->is_repeated()) {
printer->Print(
" if (f.length > 0) {\n");
} else {
- if (HasFieldPresence(field)) {
+ if (HasFieldPresence(options, field)) {
printer->Print(
" if (f != null) {\n");
} else {
@@ -2820,7 +2995,7 @@ void Generator::GenerateClassSerializeBinaryField(
}
// Write the field on the wire.
- if (field->is_map()) {
+ if (IsMap(options, field)) {
const FieldDescriptor* key_field = MapFieldKey(field);
const FieldDescriptor* value_field = MapFieldValue(field);
printer->Print(
@@ -2845,7 +3020,7 @@ void Generator::GenerateClassSerializeBinaryField(
"index", SimpleItoa(field->number()));
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
- !(field->is_map())) {
+ !IsMap(options, field)) {
printer->Print(
",\n"
" $submsg$.serializeBinaryToWriter\n",
@@ -2907,7 +3082,7 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
"class", extension_scope,
"extensionType", JSFieldTypeAnnotation(
options, field,
- /* force_optional = */ false,
+ /* is_setter_argument = */ false,
/* force_present = */ true,
/* singular_if_not_packed = */ false));
printer->Print(
@@ -2946,11 +3121,11 @@ void Generator::GenerateExtension(const GeneratorOptions& options,
"binaryMessageSerializeFn",
(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
(SubmessageTypeRef(options, field) +
- ".serializeBinaryToWriter") : "null",
+ ".serializeBinaryToWriter") : "undefined",
"binaryMessageDeserializeFn",
(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
(SubmessageTypeRef(options, field) +
- ".deserializeBinaryFromReader") : "null");
+ ".deserializeBinaryFromReader") : "undefined");
printer->Print(
" $isPacked$);\n",
@@ -3005,17 +3180,31 @@ bool GeneratorOptions::ParseFromOptions(
library = options[i].second;
} else if (options[i].first == "import_style") {
if (options[i].second == "closure") {
- import_style = IMPORT_CLOSURE;
+ import_style = kImportClosure;
} else if (options[i].second == "commonjs") {
- import_style = IMPORT_COMMONJS;
+ import_style = kImportCommonJs;
} else if (options[i].second == "browser") {
- import_style = IMPORT_BROWSER;
+ import_style = kImportBrowser;
} else if (options[i].second == "es6") {
- import_style = IMPORT_ES6;
+ import_style = kImportEs6;
} else {
*error = "Unknown import style " + options[i].second + ", expected " +
"one of: closure, commonjs, browser, es6.";
}
+ } else if (options[i].first == "extension") {
+ extension = options[i].second;
+ } else if (options[i].first == "one_output_file_per_input_file") {
+ if (!options[i].second.empty()) {
+ *error = "Unexpected option value for one_output_file_per_input_file";
+ return false;
+ }
+ one_output_file_per_input_file = true;
+ } else if (options[i].first == "broken_proto3_semantics") {
+ if (!options[i].second.empty()) {
+ *error = "Unexpected option value for broken_proto3_semantics";
+ return false;
+ }
+ broken_proto3_semantics = true;
} else {
// Assume any other option is an output directory, as long as it is a bare
// `key` rather than a `key=value` option.
@@ -3027,14 +3216,37 @@ bool GeneratorOptions::ParseFromOptions(
}
}
- if (!library.empty() && import_style != IMPORT_CLOSURE) {
- *error = "The library option should only be used for "
- "import_style=closure";
+ if (import_style != kImportClosure &&
+ (add_require_for_enums || testonly || !library.empty() ||
+ error_on_name_conflict || broken_proto3_semantics ||
+ extension != ".js" || one_output_file_per_input_file)) {
+ *error =
+ "The add_require_for_enums, testonly, library, error_on_name_conflict, "
+ "broken_proto3_semantics, extension, and "
+ "one_output_file_per_input_file options should only be used for "
+ "import_style=closure";
+ return false;
}
return true;
}
+GeneratorOptions::OutputMode GeneratorOptions::output_mode() const {
+ // We use one output file per input file if we are not using Closure or if
+ // this is explicitly requested.
+ if (import_style != kImportClosure || one_output_file_per_input_file) {
+ return kOneOutputFilePerInputFile;
+ }
+
+ // If a library name is provided, we put everything in that one file.
+ if (!library.empty()) {
+ return kEverythingInOneFile;
+ }
+
+ // Otherwise, we create one output file per type.
+ return kOneOutputFilePerType;
+}
+
void Generator::GenerateFilesInDepOrder(
const GeneratorOptions& options,
io::Printer* printer,
@@ -3081,7 +3293,7 @@ void Generator::GenerateFile(const GeneratorOptions& options,
GenerateHeader(options, printer);
// Generate "require" statements.
- if (options.import_style == GeneratorOptions::IMPORT_COMMONJS) {
+ if (options.import_style == GeneratorOptions::kImportCommonJs) {
printer->Print("var jspb = require('google-protobuf');\n");
printer->Print("var goog = jspb;\n");
printer->Print("var global = Function('return this')();\n\n");
@@ -3091,42 +3303,43 @@ void Generator::GenerateFile(const GeneratorOptions& options,
printer->Print(
"var $alias$ = require('$file$');\n",
"alias", ModuleAlias(name),
- "file", GetRootPath(file->name(), name) + GetJSFilename(name));
+ "file", GetRootPath(file->name(), name) + GetJSFilename(options, name));
}
}
- // We aren't using Closure's import system, but we use goog.exportSymbol()
- // to construct the expected tree of objects, eg.
- //
- // goog.exportSymbol('foo.bar.Baz', null, this);
- //
- // // Later generated code expects foo.bar = {} to exist:
- // foo.bar.Baz = function() { /* ... */ }
set<string> provided;
-
- // Cover the case where this file declares extensions but no messages.
- // This will ensure that the file-level object will be declared to hold
- // the extensions.
+ set<const FieldDescriptor*> extensions;
for (int i = 0; i < file->extension_count(); i++) {
- provided.insert(file->extension(i)->full_name());
+ // We honor the jspb::ignore option here only when working with
+ // Closure-style imports. Use of this option is discouraged and so we want
+ // to avoid adding new support for it.
+ if (options.import_style == GeneratorOptions::kImportClosure &&
+ IgnoreField(file->extension(i))) {
+ continue;
+ }
+ provided.insert(GetPath(options, file) + "." +
+ JSObjectFieldName(options, file->extension(i)));
+ extensions.insert(file->extension(i));
}
FindProvidesForFile(options, printer, file, &provided);
- for (std::set<string>::iterator it = provided.begin();
- it != provided.end(); ++it) {
- printer->Print("goog.exportSymbol('$name$', null, global);\n",
- "name", *it);
+ GenerateProvides(options, printer, &provided);
+ vector<const FileDescriptor*> files;
+ files.push_back(file);
+ if (options.import_style == GeneratorOptions::kImportClosure) {
+ GenerateRequiresForLibrary(options, printer, files, &provided);
}
GenerateClassesAndEnums(options, printer, file);
- // Extensions nested inside messages are emitted inside
- // GenerateClassesAndEnums().
- for (int i = 0; i < file->extension_count(); i++) {
- GenerateExtension(options, printer, file->extension(i));
+ // Generate code for top-level extensions. Extensions nested inside messages
+ // are emitted inside GenerateClassesAndEnums().
+ for (set<const FieldDescriptor*>::const_iterator it = extensions.begin();
+ it != extensions.end(); ++it) {
+ GenerateExtension(options, printer, *it);
}
- if (options.import_style == GeneratorOptions::IMPORT_COMMONJS) {
+ if (options.import_style == GeneratorOptions::kImportCommonJs) {
printer->Print("goog.object.extend(exports, $package$);\n",
"package", GetPath(options, file));
}
@@ -3144,15 +3357,10 @@ bool Generator::GenerateAll(const vector<const FileDescriptor*>& files,
}
- // There are three schemes for where output files go:
- //
- // - import_style = IMPORT_CLOSURE, library non-empty: all output in one file
- // - import_style = IMPORT_CLOSURE, library empty: one output file per type
- // - import_style != IMPORT_CLOSURE: one output file per .proto file
- if (options.import_style == GeneratorOptions::IMPORT_CLOSURE &&
- options.library != "") {
+ if (options.output_mode() == GeneratorOptions::kEverythingInOneFile) {
// All output should go in a single file.
- string filename = options.output_dir + "/" + options.library + ".js";
+ string filename = options.output_dir + "/" + options.library +
+ options.GetFileNameExtension();
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
@@ -3187,7 +3395,7 @@ bool Generator::GenerateAll(const vector<const FileDescriptor*>& files,
if (printer.failed()) {
return false;
}
- } else if (options.import_style == GeneratorOptions::IMPORT_CLOSURE) {
+ } else if (options.output_mode() == GeneratorOptions::kOneOutputFilePerType) {
set<const void*> allowed_set;
if (!GenerateJspbAllowedSet(options, files, &allowed_set, error)) {
return false;
@@ -3279,13 +3487,14 @@ bool Generator::GenerateAll(const vector<const FileDescriptor*>& files,
}
}
}
- } else {
+ } else /* options.output_mode() == kOneOutputFilePerInputFile */ {
// Generate one output file per input (.proto) file.
for (int i = 0; i < files.size(); i++) {
const google::protobuf::FileDescriptor* file = files[i];
- string filename = options.output_dir + "/" + GetJSFilename(file->name());
+ string filename =
+ options.output_dir + "/" + GetJSFilename(options, file->name());
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GOOGLE_CHECK(output.get());
io::Printer printer(output.get(), '$');
diff --git a/src/google/protobuf/compiler/js/js_generator.h b/src/google/protobuf/compiler/js/js_generator.h
index 6fd7ca50..4ca3493c 100755
--- a/src/google/protobuf/compiler/js/js_generator.h
+++ b/src/google/protobuf/compiler/js/js_generator.h
@@ -28,12 +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.
+// Generates JavaScript code for a given .proto file.
+
#ifndef GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__
#define GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__
#include <string>
#include <set>
+#include <google/protobuf/stubs/logging.h>
+#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/code_generator.h>
namespace google {
@@ -51,45 +55,80 @@ namespace compiler {
namespace js {
struct GeneratorOptions {
- // Add a `goog.requires()` call for each enum type used. If not set, a forward
- // declaration with `goog.forwardDeclare` is produced instead.
- bool add_require_for_enums;
- // Set this as a test-only module via `goog.setTestOnly();`.
- bool testonly;
// Output path.
string output_dir;
// Namespace prefix.
string namespace_prefix;
- // Create a library with name <name>_lib.js rather than a separate .js file
- // per type?
- string library;
- // Error if there are two types that would generate the same output file?
- bool error_on_name_conflict;
// Enable binary-format support?
bool binary;
// What style of imports should be used.
enum ImportStyle {
- IMPORT_CLOSURE, // goog.require()
- IMPORT_COMMONJS, // require()
- IMPORT_BROWSER, // no import statements
- IMPORT_ES6, // import { member } from ''
+ kImportClosure, // goog.require()
+ kImportCommonJs, // require()
+ kImportBrowser, // no import statements
+ kImportEs6, // import { member } from ''
} import_style;
GeneratorOptions()
- : add_require_for_enums(false),
- testonly(false),
- output_dir("."),
+ : output_dir("."),
namespace_prefix(""),
+ binary(false),
+ import_style(kImportClosure),
+ add_require_for_enums(false),
+ testonly(false),
library(""),
error_on_name_conflict(false),
- binary(false),
- import_style(IMPORT_CLOSURE) {}
+ broken_proto3_semantics(false),
+ extension(".js"),
+ one_output_file_per_input_file(false) {}
bool ParseFromOptions(
const vector< pair< string, string > >& options,
string* error);
+
+ // Returns the file name extension to use for generated code.
+ string GetFileNameExtension() const {
+ return import_style == kImportClosure ? extension : "_pb.js";
+ }
+
+ enum OutputMode {
+ // Create an output file for each input .proto file.
+ kOneOutputFilePerInputFile,
+ // Create an output file for each type.
+ kOneOutputFilePerType,
+ // Put everything in a single file named by the library option.
+ kEverythingInOneFile,
+ };
+
+ // Indicates how to output the generated code based on the provided options.
+ OutputMode output_mode() const;
+
+ // The remaining options are only relevant when we are using kImportClosure.
+
+ // Add a `goog.requires()` call for each enum type used. If not set, a
+ // forward declaration with `goog.forwardDeclare` is produced instead.
+ bool add_require_for_enums;
+ // Set this as a test-only module via `goog.setTestOnly();`.
+ bool testonly;
+ // Create a library with name <name>_lib.js rather than a separate .js file
+ // per type?
+ string library;
+ // Error if there are two types that would generate the same output file?
+ bool error_on_name_conflict;
+ // Preserve the broken proto3 semantics from the old codegen? This amounts
+ // to using proto2 field presence semantics even for proto3 files. DO NOT
+ // USE except for migrating legacy code.
+ bool broken_proto3_semantics;
+ // The extension to use for output file names.
+ string extension;
+ // Create a separate output file for each input file?
+ bool one_output_file_per_input_file;
};
+// CodeGenerator implementation which generates a JavaScript source file and
+// header. If you create your own protocol compiler binary and you want it to
+// support JavaScript output, you can do so by registering an instance of this
+// CodeGenerator with the CommandLineInterface in your main() function.
class LIBPROTOC_EXPORT Generator : public CodeGenerator {
public:
Generator() {}
@@ -201,6 +240,11 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
io::Printer* printer,
const FileDescriptor* file) const;
+ void GenerateFieldValueExpression(io::Printer* printer,
+ const char* obj_reference,
+ const FieldDescriptor* field,
+ bool use_default) const;
+
// Generate definition for one class.
void GenerateClass(const GeneratorOptions& options,
io::Printer* printer,
@@ -270,6 +314,17 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator {
io::Printer* printer,
const FieldDescriptor* field) const;
+ // Generate addFoo() method for repeated primitive fields.
+ void GenerateRepeatedPrimitiveHelperMethods(const GeneratorOptions& options,
+ io::Printer* printer,
+ const FieldDescriptor* field,
+ bool untyped) const;
+
+ // Generate addFoo() method for repeated message fields.
+ void GenerateRepeatedMessageHelperMethods(const GeneratorOptions& options,
+ io::Printer* printer,
+ const FieldDescriptor* field) const;
+
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Generator);
};
diff --git a/src/google/protobuf/compiler/main.cc b/src/google/protobuf/compiler/main.cc
index 2f3c5b8f..aca2a5b9 100644
--- a/src/google/protobuf/compiler/main.cc
+++ b/src/google/protobuf/compiler/main.cc
@@ -32,15 +32,20 @@
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
+
+#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
#include <google/protobuf/compiler/python/python_generator.h>
#include <google/protobuf/compiler/java/java_generator.h>
+#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
+
+#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
#include <google/protobuf/compiler/javanano/javanano_generator.h>
-// TODO(teboring): Add it back when php implementation is ready
-// #include <google/protobuf/compiler/php/php_generator.h>
+#include <google/protobuf/compiler/php/php_generator.h>
#include <google/protobuf/compiler/ruby/ruby_generator.h>
#include <google/protobuf/compiler/csharp/csharp_generator.h>
#include <google/protobuf/compiler/objectivec/objectivec_generator.h>
#include <google/protobuf/compiler/js/js_generator.h>
+#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
int main(int argc, char* argv[]) {
@@ -52,12 +57,15 @@ int main(int argc, char* argv[]) {
cli.RegisterGenerator("--cpp_out", "--cpp_opt", &cpp_generator,
"Generate C++ header and source.");
+#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
// Proto2 Java
google::protobuf::compiler::java::JavaGenerator java_generator;
cli.RegisterGenerator("--java_out", &java_generator,
"Generate Java source file.");
+#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
+#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
// Proto2 Python
google::protobuf::compiler::python::Generator py_generator;
cli.RegisterGenerator("--python_out", &py_generator,
@@ -68,11 +76,10 @@ int main(int argc, char* argv[]) {
cli.RegisterGenerator("--javanano_out", &javanano_generator,
"Generate Java Nano source file.");
- // TODO(teboring): Add it back when php implementation is ready
// PHP
- // google::protobuf::compiler::php::Generator php_generator;
- // cli.RegisterGenerator("--php_out", &php_generator,
- // "Generate PHP source file.");
+ google::protobuf::compiler::php::Generator php_generator;
+ cli.RegisterGenerator("--php_out", &php_generator,
+ "Generate PHP source file.");
// Ruby
google::protobuf::compiler::ruby::Generator rb_generator;
@@ -93,6 +100,7 @@ int main(int argc, char* argv[]) {
google::protobuf::compiler::js::Generator js_generator;
cli.RegisterGenerator("--js_out", &js_generator,
"Generate JavaScript source.");
+#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP
return cli.Run(argc, argv);
}
diff --git a/src/google/protobuf/compiler/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc
index 82bb3427..1cc932dd 100644
--- a/src/google/protobuf/compiler/mock_code_generator.cc
+++ b/src/google/protobuf/compiler/mock_code_generator.cc
@@ -61,7 +61,7 @@ namespace compiler {
// comma-separated string.
string CommaSeparatedList(const vector<const FileDescriptor*> all_files) {
vector<string> names;
- for (int i = 0; i < all_files.size(); i++) {
+ for (size_t i = 0; i < all_files.size(); i++) {
names.push_back(all_files[i]->name());
}
return Join(names, ",");
@@ -97,7 +97,7 @@ void MockCodeGenerator::ExpectGenerated(
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
}
- for (int i = 0; i < lines.size(); i++) {
+ for (size_t i = 0; i < lines.size(); i++) {
lines[i] += "\n";
}
@@ -114,7 +114,7 @@ void MockCodeGenerator::ExpectGenerated(
EXPECT_EQ(kFirstInsertionPoint, lines[1 + insertion_list.size()]);
EXPECT_EQ(kSecondInsertionPoint, lines[2 + insertion_list.size() * 2]);
- for (int i = 0; i < insertion_list.size(); i++) {
+ for (size_t i = 0; i < insertion_list.size(); i++) {
EXPECT_EQ(GetOutputFileContent(insertion_list[i], "first_insert",
file, file, first_message_name),
lines[1 + i]);
@@ -170,7 +170,7 @@ bool MockCodeGenerator::Generate(
SplitStringUsing(StripPrefixString(parameter, "insert="),
",", &insert_into);
- for (int i = 0; i < insert_into.size(); i++) {
+ for (size_t i = 0; i < insert_into.size(); i++) {
{
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->OpenForInsert(
GetOutputFileName(insert_into[i], file), kFirstInsertionPointName));
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
index e76f8e99..34e17823 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc
@@ -62,7 +62,7 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) {
string enum_comments;
SourceLocation location;
if (descriptor_->GetSourceLocation(&location)) {
- enum_comments = BuildCommentsString(location);
+ enum_comments = BuildCommentsString(location, true);
} else {
enum_comments = "";
}
@@ -81,16 +81,18 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) {
if (HasPreservingUnknownEnumSemantics(descriptor_->file())) {
// Include the unknown value.
printer->Print(
- "/// Value used if any message's field encounters a value that is not defined\n"
- "/// by this enum. The message will also have C functions to get/set the rawValue\n"
- "/// of the field.\n"
+ "/**\n"
+ " * Value used if any message's field encounters a value that is not defined\n"
+ " * by this enum. The message will also have C functions to get/set the rawValue\n"
+ " * of the field.\n"
+ " **/\n"
"$name$_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,\n",
"name", name_);
}
for (int i = 0; i < all_values_.size(); i++) {
SourceLocation location;
if (all_values_[i]->GetSourceLocation(&location)) {
- string comments = BuildCommentsString(location).c_str();
+ string comments = BuildCommentsString(location, true).c_str();
if (comments.length() > 0) {
if (i > 0) {
printer->Print("\n");
@@ -111,8 +113,10 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) {
"\n"
"GPBEnumDescriptor *$name$_EnumDescriptor(void);\n"
"\n"
- "/// Checks to see if the given value is defined by the enum or was not known at\n"
- "/// the time this source was generated.\n"
+ "/**\n"
+ " * Checks to see if the given value is defined by the enum or was not known at\n"
+ " * the time this source was generated.\n"
+ " **/\n"
"BOOL $name$_IsValidValue(int32_t value);\n"
"\n",
"name", name_);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
index b63bc0de..7a774a09 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc
@@ -83,12 +83,16 @@ void EnumFieldGenerator::GenerateCFunctionDeclarations(
printer->Print(
variables_,
- "/// Fetches the raw value of a @c $owning_message_class$'s @c $name$ property, even\n"
- "/// if the value was not defined by the enum at the time the code was generated.\n"
+ "/**\n"
+ " * Fetches the raw value of a @c $owning_message_class$'s @c $name$ property, even\n"
+ " * if the value was not defined by the enum at the time the code was generated.\n"
+ " **/\n"
"int32_t $owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message);\n"
- "/// Sets the raw value of an @c $owning_message_class$'s @c $name$ property, allowing\n"
- "/// it to be set to a value that was not defined by the enum at the time the code\n"
- "/// was generated.\n"
+ "/**\n"
+ " * Sets the raw value of an @c $owning_message_class$'s @c $name$ property, allowing\n"
+ " * it to be set to a value that was not defined by the enum at the time the code\n"
+ " * was generated.\n"
+ " **/\n"
"void Set$owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message, int32_t value);\n"
"\n");
}
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
index 3f7ab9d3..d0de1eca 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc
@@ -63,7 +63,7 @@ void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) {
vars["method_name"] = method_name_;
SourceLocation location;
if (descriptor_->GetSourceLocation(&location)) {
- vars["comments"] = BuildCommentsString(location);
+ vars["comments"] = BuildCommentsString(location, true);
} else {
vars["comments"] = "";
}
@@ -85,7 +85,7 @@ void ExtensionGenerator::GenerateStaticVariablesInitialization(
if (descriptor_->containing_type()->options().message_set_wire_format())
options.push_back("GPBExtensionSetWireFormat");
- vars["options"] = BuildFlagsString(options);
+ vars["options"] = BuildFlagsString(FLAGTYPE_EXTENSION, options);
ObjectiveCType objc_type = GetObjectiveCType(descriptor_);
string singular_type;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
index 812b4a1c..527b7c0c 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_field.cc
@@ -64,7 +64,7 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
SourceLocation location;
if (descriptor->GetSourceLocation(&location)) {
- (*variables)["comments"] = BuildCommentsString(location);
+ (*variables)["comments"] = BuildCommentsString(location, true);
} else {
(*variables)["comments"] = "\n";
}
@@ -93,7 +93,7 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
field_flags.push_back("GPBFieldHasEnumDescriptor");
}
- (*variables)["fieldflags"] = BuildFlagsString(field_flags);
+ (*variables)["fieldflags"] = BuildFlagsString(FLAGTYPE_FIELD, field_flags);
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["default_name"] = GPBGenericValueFieldName(descriptor);
@@ -335,7 +335,7 @@ void ObjCObjFieldGenerator::GeneratePropertyDeclaration(
if (WantsHasProperty()) {
printer->Print(
variables_,
- "/// Test to see if @c $name$ has been set.\n"
+ "/** Test to see if @c $name$ has been set. */\n"
"@property(nonatomic, readwrite) BOOL has$capitalized_name$$deprecated_attribute$;\n");
}
if (IsInitName(variables_.find("name")->second)) {
@@ -387,7 +387,7 @@ void RepeatedFieldGenerator::GeneratePropertyDeclaration(
"$comments$"
"$array_comment$"
"@property(nonatomic, readwrite, strong, null_resettable) $array_property_type$ *$name$$storage_attribute$$deprecated_attribute$;\n"
- "/// The number of items in @c $name$ without causing the array to be created.\n"
+ "/** The number of items in @c $name$ without causing the array to be created. */\n"
"@property(nonatomic, readonly) NSUInteger $name$_Count$deprecated_attribute$;\n");
if (IsInitName(variables_.find("name")->second)) {
// If property name starts with init we need to annotate it to get past ARC.
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
index b864ef12..7ad127bb 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc
@@ -37,6 +37,7 @@
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/stubs/strutil.h>
+#include <algorithm> // std::find()
#include <iostream>
#include <sstream>
@@ -45,218 +46,120 @@
namespace google {
namespace protobuf {
-
-// This is also found in GPBBootstrap.h, and needs to be kept in sync. It
-// is the version check done to ensure generated code works with the current
-// runtime being used.
-const int32 GOOGLE_PROTOBUF_OBJC_GEN_VERSION = 30001;
-
namespace compiler {
namespace objectivec {
namespace {
-class ImportWriter {
- public:
- ImportWriter(const Options& options)
- : options_(options),
- need_to_parse_mapping_file_(true) {}
-
- void AddFile(const FileGenerator* file);
- void Print(io::Printer *printer) const;
-
- private:
- class ProtoFrameworkCollector : public LineConsumer {
- public:
- ProtoFrameworkCollector(map<string, string>* inout_proto_file_to_framework_name)
- : map_(inout_proto_file_to_framework_name) {}
-
- virtual bool ConsumeLine(const StringPiece& line, string* out_error);
-
- private:
- map<string, string>* map_;
- };
+// This is also found in GPBBootstrap.h, and needs to be kept in sync.
+const int32 GOOGLE_PROTOBUF_OBJC_VERSION = 30002;
- void ParseFrameworkMappings();
+const char* kHeaderExtension = ".pbobjc.h";
- const Options options_;
- 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_;
-};
-
-void ImportWriter::AddFile(const FileGenerator* file) {
- const FileDescriptor* file_descriptor = file->Descriptor();
- const string extension(".pbobjc.h");
-
- if (IsProtobufLibraryBundledProtoFile(file_descriptor)) {
- protobuf_framework_imports_.push_back(
- FilePathBasename(file_descriptor) + extension);
- protobuf_non_framework_imports_.push_back(file->Path() + extension);
- return;
+// Checks if a message contains any extension definitions (on the message or
+// a nested message under it).
+bool MessageContainsExtensions(const Descriptor* message) {
+ if (message->extension_count() > 0) {
+ return true;
}
-
- // Lazy parse any mappings.
- if (need_to_parse_mapping_file_) {
- ParseFrameworkMappings();
+ for (int i = 0; i < message->nested_type_count(); i++) {
+ if (MessageContainsExtensions(message->nested_type(i))) {
+ return true;
+ }
}
+ return false;
+}
- map<string, string>::iterator proto_lookup =
- proto_file_to_framework_name_.find(file_descriptor->name());
- if (proto_lookup != proto_file_to_framework_name_.end()) {
- other_framework_imports_.push_back(
- proto_lookup->second + "/" +
- FilePathBasename(file_descriptor) + extension);
- return;
+// Checks if the file contains any extensions definitions (at the root or
+// nested under a message).
+bool FileContainsExtensions(const FileDescriptor* file) {
+ if (file->extension_count() > 0) {
+ return true;
}
-
- if (!options_.generate_for_named_framework.empty()) {
- other_framework_imports_.push_back(
- options_.generate_for_named_framework + "/" +
- FilePathBasename(file_descriptor) + extension);
- return;
+ for (int i = 0; i < file->message_type_count(); i++) {
+ if (MessageContainsExtensions(file->message_type(i))) {
+ return true;
+ }
}
-
- other_imports_.push_back(file->Path() + extension);
+ return false;
}
-void ImportWriter::Print(io::Printer* printer) const {
- assert(protobuf_non_framework_imports_.size() ==
- protobuf_framework_imports_.size());
-
- bool add_blank_line = false;
-
- if (protobuf_framework_imports_.size() > 0) {
- const string framework_name(ProtobufLibraryFrameworkName);
- const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name));
-
- printer->Print(
- "#if $cpp_symbol$\n",
- "cpp_symbol", cpp_symbol);
- for (vector<string>::const_iterator iter = protobuf_framework_imports_.begin();
- iter != protobuf_framework_imports_.end(); ++iter) {
- printer->Print(
- " #import <$framework_name$/$header$>\n",
- "framework_name", framework_name,
- "header", *iter);
- }
- printer->Print(
- "#else\n");
- for (vector<string>::const_iterator iter = protobuf_non_framework_imports_.begin();
- iter != protobuf_non_framework_imports_.end(); ++iter) {
- printer->Print(
- " #import \"$header$\"\n",
- "header", *iter);
- }
- printer->Print(
- "#endif\n");
-
- add_blank_line = true;
+// Helper for CollectMinimalFileDepsContainingExtensionsWorker that marks all
+// deps as visited and prunes them from the needed files list.
+void PruneFileAndDepsMarkingAsVisited(
+ const FileDescriptor* file,
+ vector<const FileDescriptor*>* files,
+ set<const FileDescriptor*>* files_visited) {
+ vector<const FileDescriptor*>::iterator iter =
+ std::find(files->begin(), files->end(), file);
+ if (iter != files->end()) {
+ files->erase(iter);
}
+ files_visited->insert(file);
+ for (int i = 0; i < file->dependency_count(); i++) {
+ PruneFileAndDepsMarkingAsVisited(file->dependency(i), files, files_visited);
+ }
+}
- if (other_framework_imports_.size() > 0) {
- if (add_blank_line) {
- printer->Print("\n");
- }
-
- for (vector<string>::const_iterator iter = other_framework_imports_.begin();
- iter != other_framework_imports_.end(); ++iter) {
- printer->Print(
- " #import <$header$>\n",
- "header", *iter);
- }
-
- add_blank_line = true;
+// Helper for CollectMinimalFileDepsContainingExtensions.
+void CollectMinimalFileDepsContainingExtensionsWorker(
+ const FileDescriptor* file,
+ vector<const FileDescriptor*>* files,
+ set<const FileDescriptor*>* files_visited) {
+ if (files_visited->find(file) != files_visited->end()) {
+ return;
}
+ files_visited->insert(file);
- if (other_imports_.size() > 0) {
- if (add_blank_line) {
- printer->Print("\n");
+ if (FileContainsExtensions(file)) {
+ files->push_back(file);
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const FileDescriptor* dep = file->dependency(i);
+ PruneFileAndDepsMarkingAsVisited(dep, files, files_visited);
}
-
- for (vector<string>::const_iterator iter = other_imports_.begin();
- iter != other_imports_.end(); ++iter) {
- printer->Print(
- " #import \"$header$\"\n",
- "header", *iter);
+ } else {
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const FileDescriptor* dep = file->dependency(i);
+ CollectMinimalFileDepsContainingExtensionsWorker(dep, files,
+ files_visited);
}
}
}
-void ImportWriter::ParseFrameworkMappings() {
- need_to_parse_mapping_file_ = false;
- if (options_.named_framework_to_proto_path_mappings_path.empty()) {
- return; // Nothing to do.
- }
-
- ProtoFrameworkCollector collector(&proto_file_to_framework_name_);
- string parse_error;
- if (!ParseSimpleFile(options_.named_framework_to_proto_path_mappings_path,
- &collector, &parse_error)) {
- cerr << "error parsing " << options_.named_framework_to_proto_path_mappings_path
- << " : " << parse_error << endl;
- cerr.flush();
+// Collect the deps of the given file that contain extensions. This can be used to
+// create the chain of roots that need to be wired together.
+//
+// NOTE: If any changes are made to this and the supporting functions, you will
+// need to manually validate what the generated code is for the test files:
+// objectivec/Tests/unittest_extension_chain_*.proto
+// There are comments about what the expected code should be line and limited
+// testing objectivec/Tests/GPBUnittestProtos2.m around compilation (#imports
+// specifically).
+void CollectMinimalFileDepsContainingExtensions(
+ const FileDescriptor* file,
+ vector<const FileDescriptor*>* files) {
+ set<const FileDescriptor*> files_visited;
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const FileDescriptor* dep = file->dependency(i);
+ CollectMinimalFileDepsContainingExtensionsWorker(dep, files,
+ &files_visited);
}
}
-bool ImportWriter::ProtoFrameworkCollector::ConsumeLine(
- const StringPiece& line, string* out_error) {
- int offset = line.find(':');
- if (offset == StringPiece::npos) {
- *out_error =
- string("Framework/proto file mapping line without colon sign: '") +
- line.ToString() + "'.";
- return false;
- }
- StringPiece framework_name(line, 0, offset);
- StringPiece proto_file_list(line, offset + 1, line.length() - offset - 1);
- StringPieceTrimWhitespace(&framework_name);
-
- int start = 0;
- while (start < proto_file_list.length()) {
- offset = proto_file_list.find(',', start);
- if (offset == StringPiece::npos) {
- offset = proto_file_list.length();
- }
-
- StringPiece proto_file(proto_file_list, start, offset - start);
- StringPieceTrimWhitespace(&proto_file);
- if (proto_file.size() != 0) {
- map<string, string>::iterator existing_entry =
- map_->find(proto_file.ToString());
- if (existing_entry != map_->end()) {
- cerr << "warning: duplicate proto file reference, replacing framework entry for '"
- << proto_file.ToString() << "' with '" << framework_name.ToString()
- << "' (was '" << existing_entry->second << "')." << endl;
- cerr.flush();
- }
-
- if (proto_file.find(' ') != StringPiece::npos) {
- cerr << "note: framework mapping file had a proto file with a space in, hopefully that isn't a missing comma: '"
- << proto_file.ToString() << "'" << endl;
- cerr.flush();
- }
-
- (*map_)[proto_file.ToString()] = framework_name.ToString();
+bool IsDirectDependency(const FileDescriptor* dep, const FileDescriptor* file) {
+ for (int i = 0; i < file->dependency_count(); i++) {
+ if (dep == file->dependency(i)) {
+ return true;
}
-
- start = offset + 1;
}
-
- return true;
+ return false;
}
} // namespace
-
FileGenerator::FileGenerator(const FileDescriptor *file, const Options& options)
: file_(file),
root_class_name_(FileClassName(file)),
- is_public_dep_(false),
options_(options) {
for (int i = 0; i < file_->enum_type_count(); i++) {
EnumGenerator *generator = new EnumGenerator(file_->enum_type(i));
@@ -275,8 +178,6 @@ FileGenerator::FileGenerator(const FileDescriptor *file, const Options& options)
}
FileGenerator::~FileGenerator() {
- STLDeleteContainerPointers(dependency_generators_.begin(),
- dependency_generators_.end());
STLDeleteContainerPointers(enum_generators_.begin(), enum_generators_.end());
STLDeleteContainerPointers(message_generators_.begin(),
message_generators_.end());
@@ -289,24 +190,28 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
// Add some verification that the generated code matches the source the
// code is being compiled with.
+ // NOTE: This captures the raw numeric values at the time the generator was
+ // compiled, since that will be the versions for the ObjC runtime at that
+ // time. The constants in the generated code will then get their values at
+ // at compile time (so checking against the headers being used to compile).
printer->Print(
- "#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != $protoc_gen_objc_version$\n"
- "#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.\n"
+ "#if GOOGLE_PROTOBUF_OBJC_VERSION < $google_protobuf_objc_version$\n"
+ "#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.\n"
+ "#endif\n"
+ "#if $google_protobuf_objc_version$ < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION\n"
+ "#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.\n"
"#endif\n"
"\n",
- "protoc_gen_objc_version",
- SimpleItoa(GOOGLE_PROTOBUF_OBJC_GEN_VERSION));
+ "google_protobuf_objc_version", SimpleItoa(GOOGLE_PROTOBUF_OBJC_VERSION));
// #import any headers for "public imports" in the proto file.
{
- ImportWriter import_writer(options_);
- const vector<FileGenerator *> &dependency_generators = DependencyGenerators();
- for (vector<FileGenerator *>::const_iterator iter =
- dependency_generators.begin();
- iter != dependency_generators.end(); ++iter) {
- if ((*iter)->IsPublicDependency()) {
- import_writer.AddFile(*iter);
- }
+ ImportWriter import_writer(
+ options_.generate_for_named_framework,
+ options_.named_framework_to_proto_path_mappings_path);
+ const string header_extension(kHeaderExtension);
+ for (int i = 0; i < file_->public_dependency_count(); i++) {
+ import_writer.AddFile(file_->public_dependency(i), header_extension);
}
import_writer.Print(printer);
}
@@ -357,14 +262,16 @@ void FileGenerator::GenerateHeader(io::Printer *printer) {
printer->Print(
"#pragma mark - $root_class_name$\n"
"\n"
- "/// Exposes the extension registry for this file.\n"
- "///\n"
- "/// The base class provides:\n"
- "/// @code\n"
- "/// + (GPBExtensionRegistry *)extensionRegistry;\n"
- "/// @endcode\n"
- "/// which is a @c GPBExtensionRegistry that includes all the extensions defined by\n"
- "/// this file and all files that it depends on.\n"
+ "/**\n"
+ " * Exposes the extension registry for this file.\n"
+ " *\n"
+ " * The base class provides:\n"
+ " * @code\n"
+ " * + (GPBExtensionRegistry *)extensionRegistry;\n"
+ " * @endcode\n"
+ " * which is a @c GPBExtensionRegistry that includes all the extensions defined by\n"
+ " * this file and all files that it depends on.\n"
+ " **/\n"
"@interface $root_class_name$ : GPBRootObject\n"
"@end\n"
"\n",
@@ -404,21 +311,41 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
// #import the runtime support.
PrintFileRuntimePreamble(printer, "GPBProtocolBuffers_RuntimeSupport.h");
+ vector<const FileDescriptor*> deps_with_extensions;
+ CollectMinimalFileDepsContainingExtensions(file_, &deps_with_extensions);
+
{
- ImportWriter import_writer(options_);
+ ImportWriter import_writer(
+ options_.generate_for_named_framework,
+ options_.named_framework_to_proto_path_mappings_path);
+ const string header_extension(kHeaderExtension);
// #import the header for this proto file.
- import_writer.AddFile(this);
+ import_writer.AddFile(file_, header_extension);
// #import the headers for anything that a plain dependency of this proto
// file (that means they were just an include, not a "public" include).
- const vector<FileGenerator *> &dependency_generators =
- DependencyGenerators();
- for (vector<FileGenerator *>::const_iterator iter =
- dependency_generators.begin();
- iter != dependency_generators.end(); ++iter) {
- if (!(*iter)->IsPublicDependency()) {
- import_writer.AddFile(*iter);
+ set<string> public_import_names;
+ for (int i = 0; i < file_->public_dependency_count(); i++) {
+ public_import_names.insert(file_->public_dependency(i)->name());
+ }
+ for (int i = 0; i < file_->dependency_count(); i++) {
+ const FileDescriptor *dep = file_->dependency(i);
+ bool public_import = (public_import_names.count(dep->name()) != 0);
+ if (!public_import) {
+ import_writer.AddFile(dep, header_extension);
+ }
+ }
+
+ // If any indirect dependency provided extensions, it needs to be directly
+ // 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 =
+ deps_with_extensions.begin();
+ iter != deps_with_extensions.end(); ++iter) {
+ if (!IsDirectDependency(*iter, file_)) {
+ import_writer.AddFile(*iter, header_extension);
}
}
@@ -458,46 +385,37 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
"@implementation $root_class_name$\n\n",
"root_class_name", root_class_name_);
- // Generate the extension initialization structures for the top level and
- // any nested messages.
- ostringstream extensions_stringstream;
- if (file_->extension_count() + file_->message_type_count() > 0) {
- io::OstreamOutputStream extensions_outputstream(&extensions_stringstream);
- io::Printer extensions_printer(&extensions_outputstream, '$');
- for (vector<ExtensionGenerator *>::iterator iter =
- extension_generators_.begin();
- iter != extension_generators_.end(); ++iter) {
- (*iter)->GenerateStaticVariablesInitialization(&extensions_printer);
- }
- for (vector<MessageGenerator *>::iterator iter =
- message_generators_.begin();
- iter != message_generators_.end(); ++iter) {
- (*iter)->GenerateStaticVariablesInitialization(&extensions_printer);
- }
- extensions_stringstream.flush();
- }
+ const bool file_contains_extensions = FileContainsExtensions(file_);
// If there were any extensions or this file has any dependencies, output
// a registry to override to create the file specific registry.
- const string& extensions_str = extensions_stringstream.str();
- if (extensions_str.length() > 0 || file_->dependency_count() > 0) {
+ if (file_contains_extensions || !deps_with_extensions.empty()) {
printer->Print(
"+ (GPBExtensionRegistry*)extensionRegistry {\n"
" // This is called by +initialize so there is no need to worry\n"
" // about thread safety and initialization of registry.\n"
" static GPBExtensionRegistry* registry = nil;\n"
" if (!registry) {\n"
- " GPBDebugCheckRuntimeVersion();\n"
+ " GPB_DEBUG_CHECK_RUNTIME_VERSIONS();\n"
" registry = [[GPBExtensionRegistry alloc] init];\n");
printer->Indent();
printer->Indent();
- if (extensions_str.length() > 0) {
+ if (file_contains_extensions) {
printer->Print(
"static GPBExtensionDescription descriptions[] = {\n");
printer->Indent();
- printer->Print(extensions_str.c_str());
+ for (vector<ExtensionGenerator *>::iterator iter =
+ extension_generators_.begin();
+ iter != extension_generators_.end(); ++iter) {
+ (*iter)->GenerateStaticVariablesInitialization(printer);
+ }
+ for (vector<MessageGenerator *>::iterator iter =
+ message_generators_.begin();
+ iter != message_generators_.end(); ++iter) {
+ (*iter)->GenerateStaticVariablesInitialization(printer);
+ }
printer->Outdent();
printer->Print(
"};\n"
@@ -510,14 +428,21 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
"}\n");
}
- const vector<FileGenerator *> &dependency_generators =
- DependencyGenerators();
- for (vector<FileGenerator *>::const_iterator iter =
- dependency_generators.begin();
- iter != dependency_generators.end(); ++iter) {
+ if (deps_with_extensions.empty()) {
+ printer->Print(
+ "// None of the imports (direct or indirect) defined extensions, so no need to add\n"
+ "// them to this registry.\n");
+ } else {
printer->Print(
- "[registry addExtensions:[$dependency$ extensionRegistry]];\n",
- "dependency", (*iter)->RootClassName());
+ "// Merge in the imports (direct or indirect) that defined extensions.\n");
+ for (vector<const FileDescriptor *>::iterator iter =
+ deps_with_extensions.begin();
+ iter != deps_with_extensions.end(); ++iter) {
+ const string root_class_name(FileClassName((*iter)));
+ printer->Print(
+ "[registry addExtensions:[$dependency$ extensionRegistry]];\n",
+ "dependency", root_class_name);
+ }
}
printer->Outdent();
@@ -526,27 +451,39 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
printer->Print(
" }\n"
" return registry;\n"
- "}\n"
- "\n");
+ "}\n");
+ } else {
+ if (file_->dependency_count() > 0) {
+ printer->Print(
+ "// No extensions in the file and none of the imports (direct or indirect)\n"
+ "// defined extensions, so no need to generate +extensionRegistry.\n");
+ } else {
+ printer->Print(
+ "// No extensions in the file and no imports, so no need to generate\n"
+ "// +extensionRegistry.\n");
+ }
}
- printer->Print("@end\n\n");
+ printer->Print("\n@end\n\n");
// File descriptor only needed if there are messages to use it.
if (message_generators_.size() > 0) {
- string syntax;
+ map<string, string> vars;
+ vars["root_class_name"] = root_class_name_;
+ vars["package"] = file_->package();
+ vars["objc_prefix"] = FileClassPrefix(file_);
switch (file_->syntax()) {
case FileDescriptor::SYNTAX_UNKNOWN:
- syntax = "GPBFileSyntaxUnknown";
+ vars["syntax"] = "GPBFileSyntaxUnknown";
break;
case FileDescriptor::SYNTAX_PROTO2:
- syntax = "GPBFileSyntaxProto2";
+ vars["syntax"] = "GPBFileSyntaxProto2";
break;
case FileDescriptor::SYNTAX_PROTO3:
- syntax = "GPBFileSyntaxProto3";
+ vars["syntax"] = "GPBFileSyntaxProto3";
break;
}
- printer->Print(
+ printer->Print(vars,
"#pragma mark - $root_class_name$_FileDescriptor\n"
"\n"
"static GPBFileDescriptor *$root_class_name$_FileDescriptor(void) {\n"
@@ -554,16 +491,24 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
" // about thread safety of the singleton.\n"
" static GPBFileDescriptor *descriptor = NULL;\n"
" if (!descriptor) {\n"
- " GPBDebugCheckRuntimeVersion();\n"
- " descriptor = [[GPBFileDescriptor alloc] initWithPackage:@\"$package$\"\n"
- " syntax:$syntax$];\n"
+ " GPB_DEBUG_CHECK_RUNTIME_VERSIONS();\n");
+ if (vars["objc_prefix"].size() > 0) {
+ printer->Print(
+ vars,
+ " descriptor = [[GPBFileDescriptor alloc] initWithPackage:@\"$package$\"\n"
+ " objcPrefix:@\"$objc_prefix$\"\n"
+ " syntax:$syntax$];\n");
+ } else {
+ printer->Print(
+ vars,
+ " descriptor = [[GPBFileDescriptor alloc] initWithPackage:@\"$package$\"\n"
+ " syntax:$syntax$];\n");
+ }
+ printer->Print(
" }\n"
" return descriptor;\n"
"}\n"
- "\n",
- "root_class_name", root_class_name_,
- "package", file_->package(),
- "syntax", syntax);
+ "\n");
}
for (vector<EnumGenerator *>::iterator iter = enum_generators_.begin();
@@ -582,24 +527,6 @@ void FileGenerator::GenerateSource(io::Printer *printer) {
"// @@protoc_insertion_point(global_scope)\n");
}
-const vector<FileGenerator *> &FileGenerator::DependencyGenerators() {
- if (file_->dependency_count() != dependency_generators_.size()) {
- set<string> public_import_names;
- for (int i = 0; i < file_->public_dependency_count(); i++) {
- public_import_names.insert(file_->public_dependency(i)->name());
- }
- for (int i = 0; i < file_->dependency_count(); i++) {
- FileGenerator *generator =
- new FileGenerator(file_->dependency(i), options_);
- const string& name = file_->dependency(i)->name();
- bool public_import = (public_import_names.count(name) != 0);
- generator->SetIsPublicDependency(public_import);
- dependency_generators_.push_back(generator);
- }
- }
- return dependency_generators_;
-}
-
// Helper to print the import of the runtime support at the top of generated
// files. This currently only supports the runtime coming from a framework
// as defined by the official CocoaPod.
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.h b/src/google/protobuf/compiler/objectivec/objectivec_file.h
index 8e4388d8..a60a6885 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_file.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_file.h
@@ -62,32 +62,17 @@ class FileGenerator {
void GenerateHeader(io::Printer* printer);
const string& RootClassName() const { return root_class_name_; }
- const string Path() const { return FilePath(file_); }
- const FileDescriptor* Descriptor() const { return file_; }
-
- bool IsPublicDependency() const { return is_public_dep_; }
-
- protected:
- void SetIsPublicDependency(bool is_public_dep) {
- is_public_dep_ = is_public_dep;
- }
private:
const FileDescriptor* file_;
string root_class_name_;
- // Access this field through the DependencyGenerators accessor call below.
- // Do not reference it directly.
- vector<FileGenerator*> dependency_generators_;
-
vector<EnumGenerator*> enum_generators_;
vector<MessageGenerator*> message_generators_;
vector<ExtensionGenerator*> extension_generators_;
- bool is_public_dep_;
const Options options_;
- const vector<FileGenerator*>& DependencyGenerators();
void PrintFileRuntimePreamble(
io::Printer* printer, const string& header_to_import) const;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
index a0b6d6cb..36407467 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc
@@ -45,10 +45,22 @@ ObjectiveCGenerator::ObjectiveCGenerator() {}
ObjectiveCGenerator::~ObjectiveCGenerator() {}
+bool ObjectiveCGenerator::HasGenerateAll() const {
+ return true;
+}
+
bool ObjectiveCGenerator::Generate(const FileDescriptor* file,
const string& parameter,
- OutputDirectory* output_directory,
+ GeneratorContext* context,
string* error) const {
+ *error = "Unimplemented Generate() method. Call GenerateAll() instead.";
+ return false;
+}
+
+bool ObjectiveCGenerator::GenerateAll(const vector<const FileDescriptor*>& files,
+ const string& parameter,
+ GeneratorContext* context,
+ string* error) const {
// -----------------------------------------------------------------
// Parse generator options. These options are passed to the compiler using the
// --objc_opt flag. The options are passed as a comma separated list of
@@ -117,29 +129,32 @@ bool ObjectiveCGenerator::Generate(const FileDescriptor* file,
// -----------------------------------------------------------------
- // Validate the objc prefix/package pairing.
- if (!ValidateObjCClassPrefix(file, generation_options, error)) {
+ // Validate the objc prefix/package pairings.
+ if (!ValidateObjCClassPrefixes(files, generation_options, error)) {
// *error will have been filled in.
return false;
}
- FileGenerator file_generator(file, generation_options);
- string filepath = FilePath(file);
+ for (int i = 0; i < files.size(); i++) {
+ const FileDescriptor* file = files[i];
+ FileGenerator file_generator(file, generation_options);
+ string filepath = FilePath(file);
- // Generate header.
- {
- scoped_ptr<io::ZeroCopyOutputStream> output(
- output_directory->Open(filepath + ".pbobjc.h"));
- io::Printer printer(output.get(), '$');
- file_generator.GenerateHeader(&printer);
- }
+ // Generate header.
+ {
+ scoped_ptr<io::ZeroCopyOutputStream> output(
+ context->Open(filepath + ".pbobjc.h"));
+ io::Printer printer(output.get(), '$');
+ file_generator.GenerateHeader(&printer);
+ }
- // Generate m file.
- {
- scoped_ptr<io::ZeroCopyOutputStream> output(
- output_directory->Open(filepath + ".pbobjc.m"));
- io::Printer printer(output.get(), '$');
- file_generator.GenerateSource(&printer);
+ // Generate m file.
+ {
+ scoped_ptr<io::ZeroCopyOutputStream> output(
+ context->Open(filepath + ".pbobjc.m"));
+ io::Printer printer(output.get(), '$');
+ file_generator.GenerateSource(&printer);
+ }
}
return true;
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
index 09266b04..b1723318 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h
@@ -41,14 +41,25 @@ namespace protobuf {
namespace compiler {
namespace objectivec {
+// CodeGenerator implementation which generates a ObjectiveC source file and
+// header. If you create your own protocol compiler binary and you want it to
+// support ObjectiveC output, you can do so by registering an instance of this
+// CodeGenerator with the CommandLineInterface in your main() function.
class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator {
public:
ObjectiveCGenerator();
~ObjectiveCGenerator();
// implements CodeGenerator ----------------------------------------
- bool Generate(const FileDescriptor* file, const string& parameter,
- OutputDirectory* output_directory, string* error) const;
+ bool HasGenerateAll() const;
+ bool Generate(const FileDescriptor* file,
+ const string& parameter,
+ GeneratorContext* context,
+ string* error) const;
+ bool GenerateAll(const vector<const FileDescriptor*>& files,
+ const string& parameter,
+ GeneratorContext* context,
+ string* error) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjectiveCGenerator);
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
index 22c7a883..c7fd96ac 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc
@@ -44,9 +44,10 @@
#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
+#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
+#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
-#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/strutil.h>
@@ -209,10 +210,14 @@ const char* const kReservedWordList[] = {
hash_set<string> kReservedWords =
MakeWordsMap(kReservedWordList, GOOGLE_ARRAYSIZE(kReservedWordList));
-string SanitizeNameForObjC(const string& input, const string& extension) {
+string SanitizeNameForObjC(const string& input,
+ const string& extension,
+ string* out_suffix_added) {
if (kReservedWords.count(input) > 0) {
+ if (out_suffix_added) *out_suffix_added = extension;
return input + extension;
}
+ if (out_suffix_added) out_suffix_added->clear();
return input;
}
@@ -261,6 +266,34 @@ bool IsSpecialName(const string& name, const string* special_names,
return false;
}
+string GetZeroEnumNameForFlagType(const FlagType flag_type) {
+ switch(flag_type) {
+ case FLAGTYPE_DESCRIPTOR_INITIALIZATION:
+ return "GPBDescriptorInitializationFlag_None";
+ case FLAGTYPE_EXTENSION:
+ return "GPBExtensionNone";
+ case FLAGTYPE_FIELD:
+ return "GPBFieldNone";
+ default:
+ GOOGLE_LOG(FATAL) << "Can't get here.";
+ return "0";
+ }
+}
+
+string GetEnumNameForFlagType(const FlagType flag_type) {
+ switch(flag_type) {
+ case FLAGTYPE_DESCRIPTOR_INITIALIZATION:
+ return "GPBDescriptorInitializationFlags";
+ case FLAGTYPE_EXTENSION:
+ return "GPBExtensionOptions";
+ case FLAGTYPE_FIELD:
+ return "GPBFieldFlags";
+ default:
+ GOOGLE_LOG(FATAL) << "Can't get here.";
+ return string();
+ }
+}
+
} // namespace
// Escape C++ trigraphs by escaping question marks to \?
@@ -307,6 +340,12 @@ string BaseFileName(const FileDescriptor* file) {
return basename;
}
+string FileClassPrefix(const FileDescriptor* file) {
+ // Default is empty string, no need to check has_objc_class_prefix.
+ string result = file->options().objc_class_prefix();
+ return result;
+}
+
string FilePath(const FileDescriptor* file) {
string output;
string basename;
@@ -337,19 +376,13 @@ string FilePathBasename(const FileDescriptor* file) {
return output;
}
-string FileClassPrefix(const FileDescriptor* file) {
- // Default is empty string, no need to check has_objc_class_prefix.
- string result = file->options().objc_class_prefix();
- return result;
-}
-
string FileClassName(const FileDescriptor* file) {
string name = FileClassPrefix(file);
name += UnderscoresToCamelCase(StripProto(BaseFileName(file)), true);
name += "Root";
// There aren't really any reserved words that end in "Root", but playing
// it safe and checking.
- return SanitizeNameForObjC(name, "_RootClass");
+ return SanitizeNameForObjC(name, "_RootClass", NULL);
}
string ClassNameWorker(const Descriptor* descriptor) {
@@ -371,11 +404,15 @@ string ClassNameWorker(const EnumDescriptor* descriptor) {
}
string ClassName(const Descriptor* descriptor) {
+ return ClassName(descriptor, NULL);
+}
+
+string ClassName(const Descriptor* descriptor, string* out_suffix_added) {
// 1. Message names are used as is (style calls for CamelCase, trust it).
// 2. Check for reserved word at the very end and then suffix things.
string prefix = FileClassPrefix(descriptor->file());
string name = ClassNameWorker(descriptor);
- return SanitizeNameForObjC(prefix + name, "_Class");
+ return SanitizeNameForObjC(prefix + name, "_Class", out_suffix_added);
}
string EnumName(const EnumDescriptor* descriptor) {
@@ -389,7 +426,7 @@ string EnumName(const EnumDescriptor* descriptor) {
// yields Fixed_Class, Fixed_Size.
string name = FileClassPrefix(descriptor->file());
name += ClassNameWorker(descriptor);
- return SanitizeNameForObjC(name, "_Enum");
+ return SanitizeNameForObjC(name, "_Enum", NULL);
}
string EnumValueName(const EnumValueDescriptor* descriptor) {
@@ -404,7 +441,7 @@ string EnumValueName(const EnumValueDescriptor* descriptor) {
const string& name = class_name + "_" + value_str;
// There aren't really any reserved words with an underscore and a leading
// capital letter, but playing it safe and checking.
- return SanitizeNameForObjC(name, "_Value");
+ return SanitizeNameForObjC(name, "_Value", NULL);
}
string EnumValueShortName(const EnumValueDescriptor* descriptor) {
@@ -441,7 +478,7 @@ string UnCamelCaseEnumShortName(const string& name) {
string ExtensionMethodName(const FieldDescriptor* descriptor) {
const string& name = NameFromFieldDescriptor(descriptor);
const string& result = UnderscoresToCamelCase(name, false);
- return SanitizeNameForObjC(result, "_Extension");
+ return SanitizeNameForObjC(result, "_Extension", NULL);
}
string FieldName(const FieldDescriptor* field) {
@@ -456,7 +493,7 @@ string FieldName(const FieldDescriptor* field) {
result += "_p";
}
}
- return SanitizeNameForObjC(result, "_p");
+ return SanitizeNameForObjC(result, "_p", NULL);
}
string FieldNameCapitalized(const FieldDescriptor* field) {
@@ -816,21 +853,26 @@ bool HasNonZeroDefaultValue(const FieldDescriptor* field) {
return false;
}
-string BuildFlagsString(const vector<string>& strings) {
+string BuildFlagsString(const FlagType flag_type,
+ const vector<string>& strings) {
if (strings.size() == 0) {
- return "0";
+ return GetZeroEnumNameForFlagType(flag_type);
+ } else if (strings.size() == 1) {
+ return strings[0];
}
- string string;
+ string string("(" + GetEnumNameForFlagType(flag_type) + ")(");
for (size_t i = 0; i != strings.size(); ++i) {
if (i > 0) {
string.append(" | ");
}
string.append(strings[i]);
}
+ string.append(")");
return string;
}
-string BuildCommentsString(const SourceLocation& location) {
+string BuildCommentsString(const SourceLocation& location,
+ bool prefer_single_line) {
const string& comments = location.leading_comments.empty()
? location.trailing_comments
: location.leading_comments;
@@ -839,15 +881,45 @@ string BuildCommentsString(const SourceLocation& location) {
while (!lines.empty() && lines.back().empty()) {
lines.pop_back();
}
- string prefix("///");
- string suffix("\n");
+ // If there are no comments, just return an empty string.
+ if (lines.size() == 0) {
+ return "";
+ }
+
+ string prefix;
+ string suffix;
string final_comments;
- for (int i = 0; i < lines.size(); i++) {
- // HeaderDoc uses '\' and '@' for markers; escape them.
- const string line = StringReplace(lines[i], "\\", "\\\\", true);
- final_comments +=
- prefix + StringReplace(line, "@", "\\@", true) + suffix;
+ string epilogue;
+
+ bool add_leading_space = false;
+
+ if (prefer_single_line && lines.size() == 1) {
+ prefix = "/** ";
+ suffix = " */\n";
+ } else {
+ prefix = "* ";
+ suffix = "\n";
+ final_comments += "/**\n";
+ epilogue = " **/\n";
+ add_leading_space = true;
}
+
+ for (int i = 0; i < lines.size(); i++) {
+ string line = StripPrefixString(lines[i], " ");
+ // HeaderDoc and appledoc use '\' and '@' for markers; escape them.
+ line = StringReplace(line, "\\", "\\\\", true);
+ line = StringReplace(line, "@", "\\@", true);
+ // Decouple / from * to not have inline comments inside comments.
+ line = StringReplace(line, "/*", "/\\*", true);
+ line = StringReplace(line, "*/", "*\\/", true);
+ line = prefix + line;
+ StripWhitespace(&line);
+ // If not a one line, need to add the first space before *, as
+ // StripWhitespace would have removed it.
+ line = (add_leading_space ? " " : "") + line;
+ final_comments += line + suffix;
+ }
+ final_comments += epilogue;
return final_comments;
}
@@ -948,28 +1020,20 @@ bool LoadExpectedPackagePrefixes(const Options &generation_options,
generation_options.expected_prefixes_path, &collector, out_error);
}
-} // namespace
-
-bool ValidateObjCClassPrefix(const FileDescriptor* file,
- const Options& generation_options,
- string* out_error) {
+bool ValidateObjCClassPrefix(
+ const FileDescriptor* file,
+ const string& expected_prefixes_path,
+ const map<string, string>& expected_package_prefixes,
+ string* out_error) {
const string prefix = file->options().objc_class_prefix();
const string package = file->package();
// NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some
// error cases, so it seems to be ok to use as a back door for warnings.
- // Load any expected package prefixes to validate against those.
- map<string, string> expected_package_prefixes;
- if (!LoadExpectedPackagePrefixes(generation_options,
- &expected_package_prefixes,
- out_error)) {
- return false;
- }
-
// Check: Error - See if there was an expected prefix for the package and
// report if it doesn't match (wrong or missing).
- map<string, string>::iterator package_match =
+ map<string, string>::const_iterator package_match =
expected_package_prefixes.find(package);
if (package_match != expected_package_prefixes.end()) {
// There was an entry, and...
@@ -990,27 +1054,11 @@ bool ValidateObjCClassPrefix(const FileDescriptor* file,
}
// If there was no prefix option, we're done at this point.
- if (prefix.length() == 0) {
+ if (prefix.empty()) {
// No prefix, nothing left to check.
return true;
}
- // Check: Error - Make sure the prefix wasn't expected for a different
- // package (overlap is allowed, but it has to be listed as an expected
- // overlap).
- for (map<string, string>::iterator i = expected_package_prefixes.begin();
- i != expected_package_prefixes.end(); ++i) {
- if (i->second == prefix) {
- *out_error =
- "error: Found 'option objc_class_prefix = \"" + prefix +
- "\";' in '" + file->name() +
- "'; that prefix is already used for 'package " + i->first +
- ";'. It can only be reused by listing it in the expected file (" +
- generation_options.expected_prefixes_path + ").";
- return false; // Only report first usage of the prefix.
- }
- }
-
// Check: Warning - Make sure the prefix is is a reasonable value according
// to Apple's rules (the checks above implicitly whitelist anything that
// doesn't meet these rules).
@@ -1032,6 +1080,56 @@ bool ValidateObjCClassPrefix(const FileDescriptor* file,
cerr.flush();
}
+ // Look for any other package that uses the same prefix.
+ string other_package_for_prefix;
+ for (map<string, string>::const_iterator i = expected_package_prefixes.begin();
+ i != expected_package_prefixes.end(); ++i) {
+ if (i->second == prefix) {
+ other_package_for_prefix = i->first;
+ break;
+ }
+ }
+
+ // Check: Warning - If the file does not have a package, check whether
+ // the prefix declared is being used by another package or not.
+ if (package.empty()) {
+ // The file does not have a package and ...
+ if (other_package_for_prefix.empty()) {
+ // ... no other package has declared that prefix.
+ cerr << endl
+ << "protoc:0: warning: File '" << file->name() << "' has no "
+ << "package. Consider adding a new package to the proto and adding '"
+ << "new.package = " << prefix << "' to the expected prefixes file ("
+ << expected_prefixes_path << ")." << endl;
+ cerr.flush();
+ } else {
+ // ... another package has declared the same prefix.
+ cerr << endl
+ << "protoc:0: warning: File '" << file->name() << "' has no package "
+ << "and package '" << other_package_for_prefix << "' already uses '"
+ << prefix << "' as its prefix. Consider either adding a new package "
+ << "to the proto, or reusing one of the packages already using this "
+ << "prefix in the expected prefixes file ("
+ << expected_prefixes_path << ")." << endl;
+ cerr.flush();
+ }
+ return true;
+ }
+
+ // Check: Error - Make sure the prefix wasn't expected for a different
+ // package (overlap is allowed, but it has to be listed as an expected
+ // overlap).
+ if (!other_package_for_prefix.empty()) {
+ *out_error =
+ "error: Found 'option objc_class_prefix = \"" + prefix +
+ "\";' in '" + file->name() +
+ "'; that prefix is already used for 'package " +
+ other_package_for_prefix + ";'. It can only be reused by listing " +
+ "it in the expected file (" +
+ expected_prefixes_path + ").";
+ return false; // Only report first usage of the prefix.
+ }
+
// Check: Warning - If the given package/prefix pair wasn't expected, issue a
// warning issue a warning suggesting it gets added to the file.
if (!expected_package_prefixes.empty()) {
@@ -1039,13 +1137,39 @@ bool ValidateObjCClassPrefix(const FileDescriptor* file,
<< "protoc:0: warning: Found unexpected 'option objc_class_prefix = \""
<< prefix << "\";' in '" << file->name() << "';"
<< " consider adding it to the expected prefixes file ("
- << generation_options.expected_prefixes_path << ")." << endl;
+ << expected_prefixes_path << ")." << endl;
cerr.flush();
}
return true;
}
+} // namespace
+
+bool ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files,
+ const Options& generation_options,
+ string* out_error) {
+ // Load the expected package prefixes, if available, to validate against.
+ map<string, string> expected_package_prefixes;
+ if (!LoadExpectedPackagePrefixes(generation_options,
+ &expected_package_prefixes,
+ out_error)) {
+ return false;
+ }
+
+ for (int i = 0; i < files.size(); i++) {
+ bool is_valid =
+ ValidateObjCClassPrefix(files[i],
+ generation_options.expected_prefixes_path,
+ expected_package_prefixes,
+ out_error);
+ if (!is_valid) {
+ return false;
+ }
+ }
+ return true;
+}
+
TextFormatDecodeData::TextFormatDecodeData() { }
TextFormatDecodeData::~TextFormatDecodeData() { }
@@ -1368,6 +1492,178 @@ bool ParseSimpleFile(
return parser.Finish();
}
+ImportWriter::ImportWriter(
+ const string& generate_for_named_framework,
+ const string& named_framework_to_proto_path_mappings_path)
+ : generate_for_named_framework_(generate_for_named_framework),
+ named_framework_to_proto_path_mappings_path_(
+ named_framework_to_proto_path_mappings_path),
+ need_to_parse_mapping_file_(true) {
+}
+
+ImportWriter::~ImportWriter() {}
+
+void ImportWriter::AddFile(const FileDescriptor* file,
+ const string& header_extension) {
+ 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);
+ return;
+ }
+
+ // Lazy parse any mappings.
+ if (need_to_parse_mapping_file_) {
+ ParseFrameworkMappings();
+ }
+
+ map<string, string>::iterator proto_lookup =
+ proto_file_to_framework_name_.find(file->name());
+ if (proto_lookup != proto_file_to_framework_name_.end()) {
+ other_framework_imports_.push_back(
+ proto_lookup->second + "/" +
+ FilePathBasename(file) + header_extension);
+ return;
+ }
+
+ if (!generate_for_named_framework_.empty()) {
+ other_framework_imports_.push_back(
+ generate_for_named_framework_ + "/" +
+ FilePathBasename(file) + header_extension);
+ return;
+ }
+
+ other_imports_.push_back(file_path + header_extension);
+}
+
+void ImportWriter::Print(io::Printer* printer) const {
+ assert(protobuf_non_framework_imports_.size() ==
+ protobuf_framework_imports_.size());
+
+ bool add_blank_line = false;
+
+ if (protobuf_framework_imports_.size() > 0) {
+ const string framework_name(ProtobufLibraryFrameworkName);
+ const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name));
+
+ printer->Print(
+ "#if $cpp_symbol$\n",
+ "cpp_symbol", cpp_symbol);
+ for (vector<string>::const_iterator iter = protobuf_framework_imports_.begin();
+ iter != protobuf_framework_imports_.end(); ++iter) {
+ printer->Print(
+ " #import <$framework_name$/$header$>\n",
+ "framework_name", framework_name,
+ "header", *iter);
+ }
+ printer->Print(
+ "#else\n");
+ for (vector<string>::const_iterator iter = protobuf_non_framework_imports_.begin();
+ iter != protobuf_non_framework_imports_.end(); ++iter) {
+ printer->Print(
+ " #import \"$header$\"\n",
+ "header", *iter);
+ }
+ printer->Print(
+ "#endif\n");
+
+ add_blank_line = true;
+ }
+
+ if (other_framework_imports_.size() > 0) {
+ if (add_blank_line) {
+ printer->Print("\n");
+ }
+
+ for (vector<string>::const_iterator iter = other_framework_imports_.begin();
+ iter != other_framework_imports_.end(); ++iter) {
+ printer->Print(
+ " #import <$header$>\n",
+ "header", *iter);
+ }
+
+ add_blank_line = true;
+ }
+
+ if (other_imports_.size() > 0) {
+ if (add_blank_line) {
+ printer->Print("\n");
+ }
+
+ for (vector<string>::const_iterator iter = other_imports_.begin();
+ iter != other_imports_.end(); ++iter) {
+ printer->Print(
+ " #import \"$header$\"\n",
+ "header", *iter);
+ }
+ }
+}
+
+void ImportWriter::ParseFrameworkMappings() {
+ need_to_parse_mapping_file_ = false;
+ if (named_framework_to_proto_path_mappings_path_.empty()) {
+ return; // Nothing to do.
+ }
+
+ ProtoFrameworkCollector collector(&proto_file_to_framework_name_);
+ string parse_error;
+ if (!ParseSimpleFile(named_framework_to_proto_path_mappings_path_,
+ &collector, &parse_error)) {
+ cerr << "error parsing " << named_framework_to_proto_path_mappings_path_
+ << " : " << parse_error << endl;
+ cerr.flush();
+ }
+}
+
+bool ImportWriter::ProtoFrameworkCollector::ConsumeLine(
+ const StringPiece& line, string* out_error) {
+ int offset = line.find(':');
+ if (offset == StringPiece::npos) {
+ *out_error =
+ string("Framework/proto file mapping line without colon sign: '") +
+ line.ToString() + "'.";
+ return false;
+ }
+ StringPiece framework_name(line, 0, offset);
+ StringPiece proto_file_list(line, offset + 1, line.length() - offset - 1);
+ StringPieceTrimWhitespace(&framework_name);
+
+ int start = 0;
+ while (start < proto_file_list.length()) {
+ offset = proto_file_list.find(',', start);
+ if (offset == StringPiece::npos) {
+ offset = proto_file_list.length();
+ }
+
+ StringPiece proto_file(proto_file_list, start, offset - start);
+ StringPieceTrimWhitespace(&proto_file);
+ if (proto_file.size() != 0) {
+ map<string, string>::iterator existing_entry =
+ map_->find(proto_file.ToString());
+ if (existing_entry != map_->end()) {
+ cerr << "warning: duplicate proto file reference, replacing framework entry for '"
+ << proto_file.ToString() << "' with '" << framework_name.ToString()
+ << "' (was '" << existing_entry->second << "')." << endl;
+ cerr.flush();
+ }
+
+ if (proto_file.find(' ') != StringPiece::npos) {
+ cerr << "note: framework mapping file had a proto file with a space in, hopefully that isn't a missing comma: '"
+ << proto_file.ToString() << "'" << endl;
+ cerr.flush();
+ }
+
+ (*map_)[proto_file.ToString()] = framework_name.ToString();
+ }
+
+ start = offset + 1;
+ }
+
+ return true;
+}
+
} // namespace objectivec
} // namespace compiler
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
index be20beee..316069e1 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
+++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Helper functions for generating ObjectiveC code.
+
#ifndef GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__
#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__
@@ -67,6 +69,9 @@ bool IsRetainedName(const string& name);
// handling under ARC.
bool IsInitName(const string& name);
+// Gets the objc_class_prefix.
+string FileClassPrefix(const FileDescriptor* file);
+
// Gets the path of the file we're going to generate (sans the .pb.h
// extension). The path will be dependent on the objectivec package
// declared in the proto package.
@@ -83,6 +88,7 @@ string FileClassName(const FileDescriptor* file);
// These return the fully-qualified class name corresponding to the given
// descriptor.
string ClassName(const Descriptor* descriptor);
+string ClassName(const Descriptor* descriptor, string* out_suffix_added);
string EnumName(const EnumDescriptor* descriptor);
// Returns the fully-qualified name of the enum value corresponding to the
@@ -137,6 +143,12 @@ enum ObjectiveCType {
OBJECTIVECTYPE_MESSAGE
};
+enum FlagType {
+ FLAGTYPE_DESCRIPTOR_INITIALIZATION,
+ FLAGTYPE_EXTENSION,
+ FLAGTYPE_FIELD
+};
+
template<class TDescriptor>
string GetOptionalDeprecatedAttribute(const TDescriptor* descriptor, bool preSpace = true, bool postNewline = false) {
if (descriptor->options().deprecated()) {
@@ -168,10 +180,12 @@ string GPBGenericValueFieldName(const FieldDescriptor* field);
string DefaultValue(const FieldDescriptor* field);
bool HasNonZeroDefaultValue(const FieldDescriptor* field);
-string BuildFlagsString(const vector<string>& strings);
+string BuildFlagsString(const FlagType type, const vector<string>& strings);
-// Builds a HeaderDoc style comment out of the comments in the .proto file.
-string BuildCommentsString(const SourceLocation& location);
+// Builds HeaderDoc/appledoc style comments out of the comments in the .proto
+// file.
+string BuildCommentsString(const SourceLocation& location,
+ bool prefer_single_line);
// The name the commonly used by the library when built as a framework.
// This lines up to the name used in the CocoaPod.
@@ -183,12 +197,12 @@ string ProtobufFrameworkImportSymbol(const string& framework_name);
// Checks if the file is one of the proto's bundled with the library.
bool IsProtobufLibraryBundledProtoFile(const FileDescriptor* file);
-// Checks the prefix for a given file and outputs any warnings needed, if
-// there are flat out errors, then out_error is filled in and the result is
-// false.
-bool ValidateObjCClassPrefix(const FileDescriptor* file,
- const Options& generation_options,
- string* out_error);
+// 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 ValidateObjCClassPrefixes(const vector<const FileDescriptor*>& files,
+ const Options& generation_options,
+ string* out_error);
// Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform
// the input into the expected output.
@@ -223,6 +237,43 @@ class LIBPROTOC_EXPORT LineConsumer {
bool ParseSimpleFile(
const string& path, LineConsumer* line_consumer, string* out_error);
+
+// Helper class for parsing framework import mappings and generating
+// import statements.
+class LIBPROTOC_EXPORT ImportWriter {
+ public:
+ ImportWriter(const string& generate_for_named_framework,
+ const string& named_framework_to_proto_path_mappings_path);
+ ~ImportWriter();
+
+ void AddFile(const FileDescriptor* file, const string& header_extension);
+ void Print(io::Printer *printer) const;
+
+ private:
+ class ProtoFrameworkCollector : public LineConsumer {
+ public:
+ ProtoFrameworkCollector(map<string, string>* inout_proto_file_to_framework_name)
+ : map_(inout_proto_file_to_framework_name) {}
+
+ virtual bool ConsumeLine(const StringPiece& line, string* out_error);
+
+ private:
+ map<string, string>* map_;
+ };
+
+ void ParseFrameworkMappings();
+
+ const string generate_for_named_framework_;
+ const string named_framework_to_proto_path_mappings_path_;
+ map<string, string> proto_file_to_framework_name_;
+ 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_;
+};
+
} // namespace objectivec
} // namespace compiler
} // namespace protobuf
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
index ac5d8aea..0bc9dc10 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc
@@ -115,7 +115,7 @@ MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor,
if (value_field_flags.find("GPBFieldHasEnumDescriptor") != string::npos) {
field_flags.push_back("GPBFieldHasEnumDescriptor");
}
- variables_["fieldflags"] = BuildFlagsString(field_flags);
+ variables_["fieldflags"] = BuildFlagsString(FLAGTYPE_FIELD, field_flags);
ObjectiveCType value_objc_type = GetObjectiveCType(value_descriptor);
const bool value_is_object_type =
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
index e1a78619..4c6e1b55 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc
@@ -331,7 +331,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) {
string message_comments;
SourceLocation location;
if (descriptor_->GetSourceLocation(&location)) {
- message_comments = BuildCommentsString(location);
+ message_comments = BuildCommentsString(location, false);
} else {
message_comments = "";
}
@@ -521,7 +521,8 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
if (descriptor_->options().message_set_wire_format()) {
init_flags.push_back("GPBDescriptorInitializationFlag_WireFormat");
}
- vars["init_flags"] = BuildFlagsString(init_flags);
+ vars["init_flags"] = BuildFlagsString(FLAGTYPE_DESCRIPTOR_INITIALIZATION,
+ init_flags);
printer->Print(
vars,
@@ -579,6 +580,19 @@ void MessageGenerator::GenerateSource(io::Printer* printer) {
" [localDescriptor setupExtensionRanges:ranges\n"
" count:(uint32_t)(sizeof(ranges) / sizeof(GPBExtensionRange))];\n");
}
+ if (descriptor_->containing_type() != NULL) {
+ string parent_class_name = ClassName(descriptor_->containing_type());
+ printer->Print(
+ " [localDescriptor setupContainingMessageClassName:GPBStringifySymbol($parent_name$)];\n",
+ "parent_name", parent_class_name);
+ }
+ string suffix_added;
+ ClassName(descriptor_, &suffix_added);
+ if (suffix_added.size() > 0) {
+ printer->Print(
+ " [localDescriptor setupMessageClassNameSuffix:@\"$suffix$\"];\n",
+ "suffix", suffix_added);
+ }
printer->Print(
" NSAssert(descriptor == nil, @\"Startup recursed!\");\n"
" descriptor = localDescriptor;\n"
diff --git a/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc b/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
index 3dda903b..5531ae24 100644
--- a/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
+++ b/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc
@@ -53,7 +53,7 @@ OneofGenerator::OneofGenerator(const OneofDescriptor* descriptor)
string comments;
SourceLocation location;
if (descriptor_->GetSourceLocation(&location)) {
- comments = BuildCommentsString(location);
+ comments = BuildCommentsString(location, true);
} else {
comments = "";
}
@@ -104,7 +104,9 @@ void OneofGenerator::GeneratePublicCasePropertyDeclaration(
void OneofGenerator::GenerateClearFunctionDeclaration(io::Printer* printer) {
printer->Print(
variables_,
- "/// Clears whatever value was set for the oneof '$name$'.\n"
+ "/**\n"
+ " * Clears whatever value was set for the oneof '$name$'.\n"
+ " **/\n"
"void $owning_message_class$_Clear$capitalized_name$OneOfCase($owning_message_class$ *message);\n");
}
diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc
index 214d7c9c..09c7a2b6 100644
--- a/src/google/protobuf/compiler/parser.cc
+++ b/src/google/protobuf/compiler/parser.cc
@@ -525,7 +525,6 @@ bool Parser::Parse(io::Tokenizer* input, FileDescriptorProto* file) {
SourceCodeInfo source_code_info;
source_code_info_ = &source_code_info;
- vector<string> top_doc_comments;
if (LookingAtType(io::Tokenizer::TYPE_START)) {
// Advance to first token.
input_->NextWithComments(NULL, &upcoming_detached_comments_,
@@ -571,6 +570,7 @@ bool Parser::Parse(io::Tokenizer* input, FileDescriptorProto* file) {
input_ = NULL;
source_code_info_ = NULL;
+ assert(file != NULL);
source_code_info.Swap(file->mutable_source_code_info());
return !had_errors_;
}
diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc
new file mode 100644
index 00000000..75ddb405
--- /dev/null
+++ b/src/google/protobuf/compiler/php/php_generator.cc
@@ -0,0 +1,781 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <google/protobuf/compiler/php/php_generator.h>
+
+#include <google/protobuf/compiler/code_generator.h>
+#include <google/protobuf/compiler/plugin.h>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/io/printer.h>
+#include <google/protobuf/io/zero_copy_stream.h>
+#include <google/protobuf/stubs/strutil.h>
+
+#include <sstream>
+
+using google::protobuf::internal::scoped_ptr;
+
+const std::string kDescriptorFile = "google/protobuf/descriptor.proto";
+const std::string kDescriptorPackageName = "Google\\Protobuf\\Internal";
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace php {
+
+// Forward decls.
+std::string PhpName(const std::string& full_name, bool is_descriptor);
+std::string DefaultForField(google::protobuf::FieldDescriptor* field);
+std::string IntToString(int32 value);
+std::string GeneratedFileName(const std::string& proto_file,
+ bool is_descriptor);
+std::string LabelForField(google::protobuf::FieldDescriptor* field);
+std::string TypeName(google::protobuf::FieldDescriptor* field);
+std::string UnderscoresToCamelCase(const string& name, bool cap_first_letter);
+std::string EscapeDollor(const string& to_escape);
+std::string BinaryToHex(const string& binary);
+void GenerateMessage(const string& name_prefix,
+ const google::protobuf::Descriptor* message,
+ bool is_descriptor,
+ google::protobuf::io::Printer* printer);
+void GenerateEnum(const google::protobuf::EnumDescriptor* en,
+ google::protobuf::io::Printer* printer);
+void Indent(google::protobuf::io::Printer* printer);
+void Outdent(google::protobuf::io::Printer* printer);
+
+std::string MessageName(const google::protobuf::Descriptor* message,
+ bool is_descriptor) {
+ string message_name = message->name();
+ const google::protobuf::Descriptor* descriptor = message->containing_type();
+ while (descriptor != NULL) {
+ message_name = descriptor->name() + '_' + message_name;
+ descriptor = descriptor->containing_type();
+ }
+ return PhpName(message->file()->package(), is_descriptor) + '\\' +
+ message_name;
+}
+
+std::string MessageFullName(const google::protobuf::Descriptor* message,
+ bool is_descriptor) {
+ if (is_descriptor) {
+ return StringReplace(message->full_name(),
+ "google.protobuf",
+ "google.protobuf.internal", false);
+ } else {
+ return message->full_name();
+ }
+}
+
+std::string EnumFullName(const google::protobuf::EnumDescriptor* envm,
+ bool is_descriptor) {
+ if (is_descriptor) {
+ return StringReplace(envm->full_name(),
+ "google.protobuf",
+ "google.protobuf.internal", false);
+ } else {
+ return envm->full_name();
+ }
+}
+
+std::string EnumClassName(const google::protobuf::EnumDescriptor* envm) {
+ string enum_class_name = envm->name();
+ const google::protobuf::Descriptor* descriptor = envm->containing_type();
+ while (descriptor != NULL) {
+ enum_class_name = descriptor->name() + '_' + enum_class_name;
+ descriptor = descriptor->containing_type();
+ }
+ return enum_class_name;
+}
+
+std::string EnumName(const google::protobuf::EnumDescriptor* envm,
+ bool is_descriptor) {
+ string enum_name = EnumClassName(envm);
+ return PhpName(envm->file()->package(), is_descriptor) + '\\' + enum_name;
+}
+
+std::string PhpName(const std::string& full_name, bool is_descriptor) {
+ if (is_descriptor) {
+ return kDescriptorPackageName;
+ }
+
+ std::string result;
+ bool cap_next_letter = true;
+ for (int i = 0; i < full_name.size(); i++) {
+ if ('a' <= full_name[i] && full_name[i] <= 'z' && cap_next_letter) {
+ result += full_name[i] + ('A' - 'a');
+ cap_next_letter = false;
+ } else if (full_name[i] == '.') {
+ result += '\\';
+ cap_next_letter = true;
+ } else {
+ result += full_name[i];
+ cap_next_letter = false;
+ }
+ }
+ return result;
+}
+
+std::string DefaultForField(const google::protobuf::FieldDescriptor* field) {
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_INT32:
+ case FieldDescriptor::TYPE_INT64:
+ case FieldDescriptor::TYPE_UINT32:
+ case FieldDescriptor::TYPE_UINT64:
+ case FieldDescriptor::TYPE_SINT32:
+ case FieldDescriptor::TYPE_SINT64:
+ case FieldDescriptor::TYPE_FIXED32:
+ case FieldDescriptor::TYPE_FIXED64:
+ case FieldDescriptor::TYPE_SFIXED32:
+ case FieldDescriptor::TYPE_SFIXED64:
+ case FieldDescriptor::TYPE_ENUM: return "0";
+ case FieldDescriptor::TYPE_DOUBLE:
+ case FieldDescriptor::TYPE_FLOAT: return "0.0";
+ case FieldDescriptor::TYPE_BOOL: return "false";
+ case FieldDescriptor::TYPE_STRING:
+ case FieldDescriptor::TYPE_BYTES: return "''";
+ case FieldDescriptor::TYPE_MESSAGE:
+ case FieldDescriptor::TYPE_GROUP: return "null";
+ default: assert(false); return "";
+ }
+}
+
+std::string GeneratedFileName(const std::string& proto_file,
+ bool is_descriptor) {
+ if (is_descriptor) {
+ return "descriptor_internal.pb.php";
+ } else {
+ int lastindex = proto_file.find_last_of(".");
+ return proto_file.substr(0, lastindex) + ".pb.php";
+ }
+}
+
+std::string IntToString(int32 value) {
+ std::ostringstream os;
+ os << value;
+ return os.str();
+}
+
+std::string LabelForField(const google::protobuf::FieldDescriptor* field) {
+ switch (field->label()) {
+ case FieldDescriptor::LABEL_OPTIONAL: return "optional";
+ case FieldDescriptor::LABEL_REQUIRED: return "required";
+ case FieldDescriptor::LABEL_REPEATED: return "repeated";
+ default: assert(false); return "";
+ }
+}
+
+std::string TypeName(const google::protobuf::FieldDescriptor* field) {
+ switch (field->type()) {
+ case FieldDescriptor::TYPE_INT32: return "int32";
+ case FieldDescriptor::TYPE_INT64: return "int64";
+ case FieldDescriptor::TYPE_UINT32: return "uint32";
+ case FieldDescriptor::TYPE_UINT64: return "uint64";
+ case FieldDescriptor::TYPE_SINT32: return "sint32";
+ case FieldDescriptor::TYPE_SINT64: return "sint64";
+ case FieldDescriptor::TYPE_FIXED32: return "fixed32";
+ case FieldDescriptor::TYPE_FIXED64: return "fixed64";
+ case FieldDescriptor::TYPE_SFIXED32: return "sfixed32";
+ case FieldDescriptor::TYPE_SFIXED64: return "sfixed64";
+ case FieldDescriptor::TYPE_DOUBLE: return "double";
+ case FieldDescriptor::TYPE_FLOAT: return "float";
+ case FieldDescriptor::TYPE_BOOL: return "bool";
+ case FieldDescriptor::TYPE_ENUM: return "enum";
+ case FieldDescriptor::TYPE_STRING: return "string";
+ case FieldDescriptor::TYPE_BYTES: return "bytes";
+ case FieldDescriptor::TYPE_MESSAGE: return "message";
+ case FieldDescriptor::TYPE_GROUP: return "group";
+ default: assert(false); return "";
+ }
+}
+
+std::string EnumOrMessageSuffix(
+ const google::protobuf::FieldDescriptor* field, bool is_descriptor) {
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ return ", '" + MessageFullName(field->message_type(), is_descriptor) + "'";
+ }
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
+ return ", '" + EnumFullName(field->enum_type(), is_descriptor) + "'";
+ }
+ return "";
+}
+
+// Converts a name to camel-case. If cap_first_letter is true, capitalize the
+// first letter.
+std::string UnderscoresToCamelCase(const string& input, bool cap_first_letter) {
+ std::string result;
+ for (int i = 0; i < input.size(); i++) {
+ if ('a' <= input[i] && input[i] <= 'z') {
+ if (cap_first_letter) {
+ result += input[i] + ('A' - 'a');
+ } else {
+ result += input[i];
+ }
+ cap_first_letter = false;
+ } else if ('A' <= input[i] && input[i] <= 'Z') {
+ if (i == 0 && !cap_first_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_first_letter = false;
+ } else if ('0' <= input[i] && input[i] <= '9') {
+ result += input[i];
+ cap_first_letter = true;
+ } else {
+ cap_first_letter = true;
+ }
+ }
+ // Add a trailing "_" if the name should be altered.
+ if (input[input.size() - 1] == '#') {
+ result += '_';
+ }
+ return result;
+}
+
+std::string EscapeDollor(const string& to_escape) {
+ return StringReplace(to_escape, "$", "\\$", true);
+}
+
+std::string BinaryToHex(const string& src) {
+ string dest;
+ size_t i;
+ unsigned char symbol[16] = {
+ '0', '1', '2', '3',
+ '4', '5', '6', '7',
+ '8', '9', 'a', 'b',
+ 'c', 'd', 'e', 'f',
+ };
+
+ dest.resize(src.size() * 2);
+ char* append_ptr = &dest[0];
+
+ for (i = 0; i < src.size(); i++) {
+ *append_ptr++ = symbol[(src[i] & 0xf0) >> 4];
+ *append_ptr++ = symbol[src[i] & 0x0f];
+ }
+
+ return dest;
+}
+
+void Indent(google::protobuf::io::Printer* printer) {
+ printer->Indent();
+ printer->Indent();
+}
+void Outdent(google::protobuf::io::Printer* printer) {
+ printer->Outdent();
+ printer->Outdent();
+}
+
+void GenerateField(const google::protobuf::FieldDescriptor* field,
+ google::protobuf::io::Printer* printer, bool is_descriptor) {
+ if (field->is_repeated()) {
+ printer->Print(
+ "private $@name@;\n",
+ "name", field->name());
+ } else if (field->containing_oneof()) {
+ // Oneof fields are handled by GenerateOneofField.
+ return;
+ } else {
+ printer->Print(
+ "private $@name@ = @default@;\n",
+ "name", field->name(),
+ "default", DefaultForField(field));
+ }
+
+ if (is_descriptor) {
+ printer->Print(
+ "private $has_@name@ = false;\n",
+ "name", field->name());
+ }
+}
+
+void GenerateOneofField(const google::protobuf::OneofDescriptor* oneof,
+ google::protobuf::io::Printer* printer) {
+ // Oneof property needs to be protected in order to be accessed by parent
+ // class in implementation.
+ printer->Print(
+ "protected $@name@;\n",
+ "name", oneof->name());
+}
+
+void GenerateFieldAccessor(const google::protobuf::FieldDescriptor* field,
+ bool is_descriptor,
+ google::protobuf::io::Printer* printer) {
+ const OneofDescriptor* oneof = field->containing_oneof();
+
+ // Generate getter.
+ if (oneof != NULL) {
+ printer->Print(
+ "public function get@camel_name@()\n"
+ "{\n"
+ " return $this->readOneof(@number@);\n"
+ "}\n\n",
+ "camel_name", UnderscoresToCamelCase(field->name(), true),
+ "number", IntToString(field->number()));
+ } else {
+ printer->Print(
+ "public function get@camel_name@()\n"
+ "{\n"
+ " return $this->@name@;\n"
+ "}\n\n",
+ "camel_name", UnderscoresToCamelCase(field->name(), true), "name",
+ field->name());
+ }
+
+ // Generate setter.
+ printer->Print(
+ "public function set@camel_name@(@var@)\n"
+ "{\n",
+ "camel_name", UnderscoresToCamelCase(field->name(), true),
+ "var", (field->is_repeated() ||
+ field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) ?
+ "&$var": "$var");
+
+ Indent(printer);
+
+ // Type check.
+ if (field->is_map()) {
+ } else if (field->is_repeated()) {
+ printer->Print(
+ "GPBUtil::checkRepeatedField($var, GPBType::@type@",
+ "type", ToUpper(field->type_name()));
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ printer->Print(
+ ", \\@class_name@);\n",
+ "class_name",
+ MessageName(field->message_type(), is_descriptor) + "::class");
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
+ printer->Print(
+ ", @class_name@);\n",
+ "class_name",
+ EnumName(field->enum_type(), is_descriptor) + "::class");
+ } else {
+ printer->Print(");\n");
+ }
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ printer->Print(
+ "GPBUtil::checkMessage($var, \\@class_name@::class);\n",
+ "class_name", MessageName(field->message_type(), is_descriptor));
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
+ printer->Print(
+ "GPBUtil::checkEnum($var, \\@class_name@::class);\n",
+ "class_name", EnumName(field->enum_type(), is_descriptor));
+ } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
+ printer->Print(
+ "GPBUtil::checkString($var, @utf8@);\n",
+ "utf8",
+ field->type() == FieldDescriptor::TYPE_STRING ? "True": "False");
+ } else {
+ printer->Print(
+ "GPBUtil::check@type@($var);\n",
+ "type", UnderscoresToCamelCase(field->cpp_type_name(), true));
+ }
+
+ if (oneof != NULL) {
+ printer->Print(
+ "$this->writeOneof(@number@, $var);\n",
+ "number", IntToString(field->number()));
+ } else {
+ printer->Print(
+ "$this->@name@ = $var;\n",
+ "name", field->name());
+ }
+
+ // Set has bit for proto2 only.
+ if (is_descriptor) {
+ printer->Print(
+ "$this->has_@field_name@ = true;\n",
+ "field_name", field->name());
+ }
+
+ Outdent(printer);
+
+ printer->Print(
+ "}\n\n");
+
+ // Generate has method for proto2 only.
+ if (is_descriptor) {
+ printer->Print(
+ "public function has@camel_name@()\n"
+ "{\n"
+ " return $this->has_@field_name@;\n"
+ "}\n\n",
+ "camel_name", UnderscoresToCamelCase(field->name(), true),
+ "field_name", field->name());
+ }
+}
+
+void GenerateRepeatedFieldDecode(
+ const google::protobuf::FieldDescriptor* field,
+ google::protobuf::io::Printer* printer) {
+ printer->Print(
+ "if ($input->read@cap_wire_type@($var)) return False;\n"
+ "$this->get@cap_field_name@() []= $var;\n",
+ "cap_field_name", UnderscoresToCamelCase(field->name(), true),
+ "cap_wire_type", UnderscoresToCamelCase(field->type_name(), true));
+}
+
+void GeneratePrimitiveFieldDecode(
+ const google::protobuf::FieldDescriptor* field,
+ google::protobuf::io::Printer* printer) {
+ printer->Print(
+ "if ($input->read@cap_wire_type@($var)) return False;\n"
+ "$this->set@cap_field_name@($var);\n",
+ "cap_field_name", UnderscoresToCamelCase(field->name(), true),
+ "cap_wire_type", UnderscoresToCamelCase(field->type_name(), true));
+}
+
+void GenerateFieldDecode(const google::protobuf::FieldDescriptor* field,
+ google::protobuf::io::Printer* printer) {
+ printer->Print(
+ "case @number@:\n",
+ "number", IntToString(field->number()));
+ Indent(printer);
+
+ if (field->is_repeated()) {
+ GenerateRepeatedFieldDecode(field, printer);
+ } else {
+ GeneratePrimitiveFieldDecode(field, printer);
+ }
+
+ printer->Print(
+ "break;\n");
+ Outdent(printer);
+}
+
+void GenerateMessage(const string& name_prefix,
+ const google::protobuf::Descriptor* message,
+ bool is_descriptor,
+ google::protobuf::io::Printer* printer) {
+ // Don't generate MapEntry messages -- we use the PHP extension's native
+ // support for map fields instead.
+ if (message->options().map_entry()) {
+ return;
+ }
+
+ string message_name = name_prefix.empty()?
+ message->name() : name_prefix + "_" + message->name();
+
+ printer->Print(
+ "class @name@ extends \\Google\\Protobuf\\Internal\\Message\n"
+ "{\n",
+ "name", message_name);
+ Indent(printer);
+
+ // Field and oneof definitions.
+ for (int i = 0; i < message->field_count(); i++) {
+ const FieldDescriptor* field = message->field(i);
+ GenerateField(field, printer, is_descriptor);
+ }
+ for (int i = 0; i < message->oneof_decl_count(); i++) {
+ const OneofDescriptor* oneof = message->oneof_decl(i);
+ GenerateOneofField(oneof, printer);
+ }
+ printer->Print("\n");
+
+ // Field and oneof accessors.
+ for (int i = 0; i < message->field_count(); i++) {
+ const FieldDescriptor* field = message->field(i);
+ GenerateFieldAccessor(field, is_descriptor, printer);
+ }
+ for (int i = 0; i < message->oneof_decl_count(); i++) {
+ const google::protobuf::OneofDescriptor* oneof = message->oneof_decl(i);
+ printer->Print(
+ "public function get@camel_name@()\n"
+ "{\n"
+ " return $this->@name@;\n"
+ "}\n\n",
+ "camel_name", UnderscoresToCamelCase(oneof->name(), true), "name",
+ oneof->name());
+ }
+
+ Outdent(printer);
+ printer->Print("}\n\n");
+
+ // Nested messages and enums.
+ for (int i = 0; i < message->nested_type_count(); i++) {
+ GenerateMessage(message_name, message->nested_type(i), is_descriptor,
+ printer);
+ }
+ for (int i = 0; i < message->enum_type_count(); i++) {
+ GenerateEnum(message->enum_type(i), printer);
+ }
+}
+
+void GenerateEnumToPool(const google::protobuf::EnumDescriptor* en,
+ bool is_descriptor,
+ google::protobuf::io::Printer* printer) {
+ printer->Print(
+ "$pool->addEnum('@name@', @class_name@::class)\n",
+ "name", EnumFullName(en, is_descriptor),
+ "class_name", en->name());
+ Indent(printer);
+
+ for (int i = 0; i < en->value_count(); i++) {
+ const EnumValueDescriptor* value = en->value(i);
+ printer->Print(
+ "->value(\"@name@\", @number@)\n",
+ "name", value->name(),
+ "number", IntToString(value->number()));
+ }
+ printer->Print("->finalizeToPool();\n\n");
+ Outdent(printer);
+}
+
+void GenerateMessageToPool(const string& name_prefix,
+ const google::protobuf::Descriptor* message,
+ bool is_descriptor,
+ google::protobuf::io::Printer* printer) {
+ // Don't generate MapEntry messages -- we use the PHP extension's native
+ // support for map fields instead.
+ if (message->options().map_entry()) {
+ return;
+ }
+ string class_name = name_prefix.empty()?
+ message->name() : name_prefix + "_" + message->name();
+
+ printer->Print(
+ "$pool->addMessage('@message@', @class_name@::class)\n",
+ "message", MessageFullName(message, is_descriptor),
+ "class_name", class_name);
+
+ Indent(printer);
+
+ for (int i = 0; i < message->field_count(); i++) {
+ const FieldDescriptor* field = message->field(i);
+ if (field->is_map()) {
+ const FieldDescriptor* key =
+ field->message_type()->FindFieldByName("key");
+ const FieldDescriptor* val =
+ field->message_type()->FindFieldByName("value");
+ printer->Print(
+ "->map('@field@', GPBType::@key@, "
+ "GPBType::@value@, @number@@other@)\n",
+ "field", field->name(),
+ "key", ToUpper(key->type_name()),
+ "value", ToUpper(val->type_name()),
+ "number", SimpleItoa(field->number()),
+ "other", EnumOrMessageSuffix(val, is_descriptor));
+ } else if (!field->containing_oneof()) {
+ printer->Print(
+ "->@label@('@field@', GPBType::@type@, @number@@other@)\n",
+ "field", field->name(),
+ "label", LabelForField(field),
+ "type", ToUpper(field->type_name()),
+ "number", SimpleItoa(field->number()),
+ "other", EnumOrMessageSuffix(field, is_descriptor));
+ }
+ }
+
+ // oneofs.
+ for (int i = 0; i < message->oneof_decl_count(); i++) {
+ const OneofDescriptor* oneof = message->oneof_decl(i);
+ printer->Print("->oneof(@name@)\n",
+ "name", oneof->name());
+ Indent(printer);
+ for (int index = 0; index < oneof->field_count(); index++) {
+ const FieldDescriptor* field = oneof->field(index);
+ printer->Print(
+ "->value('@field@', GPBType::@type@, @number@@other@)\n",
+ "field", field->name(),
+ "type", ToUpper(field->type_name()),
+ "number", SimpleItoa(field->number()),
+ "other", EnumOrMessageSuffix(field, is_descriptor));
+ }
+ printer->Print("->finish()\n");
+ Outdent(printer);
+ }
+
+ printer->Print(
+ "->finalizeToPool();\n");
+
+ Outdent(printer);
+
+ printer->Print(
+ "\n");
+
+ for (int i = 0; i < message->nested_type_count(); i++) {
+ GenerateMessageToPool(class_name, message->nested_type(i), is_descriptor,
+ printer);
+ }
+ for (int i = 0; i < message->enum_type_count(); i++) {
+ GenerateEnumToPool(message->enum_type(i), is_descriptor, printer);
+ }
+}
+
+void GenerateAddFileToPool(const google::protobuf::FileDescriptor* file,
+ bool is_descriptor,
+ google::protobuf::io::Printer* printer) {
+ if (is_descriptor) {
+ printer->Print("$pool = DescriptorPool::getGeneratedPool();\n\n");
+
+ for (int i = 0; i < file->message_type_count(); i++) {
+ GenerateMessageToPool("", file->message_type(i), is_descriptor, printer);
+ }
+ for (int i = 0; i < file->enum_type_count(); i++) {
+ GenerateEnumToPool(file->enum_type(i), is_descriptor, printer);
+ }
+
+ printer->Print(
+ "$pool->finish();\n");
+ } else {
+ // Add messages and enums to descriptor pool.
+ printer->Print("$pool = DescriptorPool::getGeneratedPool();\n\n");
+
+ FileDescriptorSet files;
+ FileDescriptorProto* file_proto = files.add_file();
+ file->CopyTo(file_proto);
+ string files_data;
+ files.SerializeToString(&files_data);
+
+ printer->Print("$pool->internalAddGeneratedFile(hex2bin(\n");
+ Indent(printer);
+
+ // Only write 30 bytes per line.
+ static const int kBytesPerLine = 30;
+ for (int i = 0; i < files_data.size(); i += kBytesPerLine) {
+ printer->Print(
+ "\"@data@\"@dot@\n",
+ "data", BinaryToHex(files_data.substr(i, kBytesPerLine)),
+ "dot", i + kBytesPerLine < files_data.size() ? " ." : "");
+ }
+
+ Outdent(printer);
+ printer->Print(
+ "));\n\n");
+ }
+
+}
+
+void GenerateEnum(const google::protobuf::EnumDescriptor* en,
+ google::protobuf::io::Printer* printer) {
+ printer->Print(
+ "class @name@\n"
+ "{\n",
+ "name", EnumClassName(en));
+ Indent(printer);
+
+ for (int i = 0; i < en->value_count(); i++) {
+ const EnumValueDescriptor* value = en->value(i);
+ printer->Print("const @name@ = @number@;\n",
+ "name", value->name(),
+ "number", IntToString(value->number()));
+ }
+ Outdent(printer);
+ printer->Print("}\n\n");
+}
+
+void GenerateUseDeclaration(bool is_descriptor,
+ google::protobuf::io::Printer* printer) {
+ if (!is_descriptor) {
+ printer->Print(
+ "use Google\\Protobuf\\Internal\\DescriptorPool;\n"
+ "use Google\\Protobuf\\Internal\\GPBType;\n"
+ "use Google\\Protobuf\\Internal\\RepeatedField;\n"
+ "use Google\\Protobuf\\Internal\\GPBUtil;\n\n");
+ } else {
+ printer->Print(
+ "use Google\\Protobuf\\Internal\\DescriptorPool;\n"
+ "use Google\\Protobuf\\Internal\\GPBType;\n"
+ "use Google\\Protobuf\\Internal\\GPBWire;\n"
+ "use Google\\Protobuf\\Internal\\RepeatedField;\n"
+ "use Google\\Protobuf\\Internal\\InputStream;\n\n"
+ "use Google\\Protobuf\\Internal\\GPBUtil;\n\n");
+ }
+}
+
+void GenerateFile(const google::protobuf::FileDescriptor* file,
+ bool is_descriptor, google::protobuf::io::Printer* printer) {
+ printer->Print(
+ "<?php\n"
+ "# Generated by the protocol buffer compiler. DO NOT EDIT!\n"
+ "# source: @filename@\n"
+ "\n",
+ "filename", file->name());
+ if (!file->package().empty()) {
+ printer->Print("namespace @name@;\n\n",
+ "name", PhpName(file->package(), is_descriptor));
+ }
+
+ for (int i = 0; i < file->dependency_count(); i++) {
+ const std::string& name = file->dependency(i)->name();
+ printer->Print("require_once('@name@');\n", "name",
+ GeneratedFileName(name, is_descriptor));
+ }
+
+ GenerateUseDeclaration(is_descriptor, printer);
+
+ for (int i = 0; i < file->message_type_count(); i++) {
+ GenerateMessage("", file->message_type(i), is_descriptor, printer);
+ }
+ for (int i = 0; i < file->enum_type_count(); i++) {
+ GenerateEnum(file->enum_type(i), printer);
+ }
+
+ GenerateAddFileToPool(file, is_descriptor, printer);
+}
+
+bool Generator::Generate(
+ const FileDescriptor* file,
+ const string& parameter,
+ GeneratorContext* generator_context,
+ string* error) const {
+ bool is_descriptor = parameter == "internal";
+
+ if (is_descriptor && file->name() != kDescriptorFile) {
+ *error =
+ "Can only generate PHP code for google/protobuf/descriptor.proto.\n";
+ return false;
+ }
+
+ if (!is_descriptor && file->syntax() != FileDescriptor::SYNTAX_PROTO3) {
+ *error =
+ "Can only generate PHP code for proto3 .proto files.\n"
+ "Please add 'syntax = \"proto3\";' to the top of your .proto file.\n";
+ return false;
+ }
+
+ std::string filename = GeneratedFileName(file->name(), is_descriptor);
+ scoped_ptr<io::ZeroCopyOutputStream> output(
+ generator_context->Open(filename));
+ io::Printer printer(output.get(), '@');
+
+ GenerateFile(file, is_descriptor, &printer);
+
+ return true;
+}
+
+} // namespace php
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/compiler/php/php_generator.h b/src/google/protobuf/compiler/php/php_generator.h
new file mode 100644
index 00000000..ce2b000a
--- /dev/null
+++ b/src/google/protobuf/compiler/php/php_generator.h
@@ -0,0 +1,57 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__
+#define GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__
+
+#include <google/protobuf/compiler/code_generator.h>
+
+#include <string>
+
+namespace google {
+namespace protobuf {
+namespace compiler {
+namespace php {
+
+class LIBPROTOC_EXPORT Generator
+ : public google::protobuf::compiler::CodeGenerator {
+ virtual bool Generate(
+ const FileDescriptor* file,
+ const string& parameter,
+ GeneratorContext* generator_context,
+ string* error) const;
+};
+
+} // namespace php
+} // namespace compiler
+} // namespace protobuf
+} // namespace google
+
+#endif // GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__
diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc
index 2ff50f61..e1087601 100644
--- a/src/google/protobuf/compiler/plugin.cc
+++ b/src/google/protobuf/compiler/plugin.cc
@@ -118,35 +118,16 @@ bool GenerateCode(const CodeGeneratorRequest& request,
GeneratorResponseContext context(response, parsed_files);
- if (generator.HasGenerateAll()) {
- string error;
- bool succeeded = generator.GenerateAll(
- parsed_files, request.parameter(), &context, &error);
-
- if (!succeeded && error.empty()) {
- error = "Code generator returned false but provided no error "
- "description.";
- }
- if (!error.empty()) {
- response->set_error(error);
- }
- } else {
- for (int i = 0; i < parsed_files.size(); i++) {
- const FileDescriptor* file = parsed_files[i];
-
- string error;
- bool succeeded = generator.Generate(
- file, request.parameter(), &context, &error);
-
- if (!succeeded && error.empty()) {
- error = "Code generator returned false but provided no error "
- "description.";
- }
- if (!error.empty()) {
- response->set_error(file->name() + ": " + error);
- break;
- }
- }
+ string error;
+ bool succeeded = generator.GenerateAll(
+ parsed_files, request.parameter(), &context, &error);
+
+ if (!succeeded && error.empty()) {
+ error = "Code generator returned false but provided no error "
+ "description.";
+ }
+ if (!error.empty()) {
+ response->set_error(error);
}
return true;
diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc
index 9064c382..a4d4a530 100644
--- a/src/google/protobuf/compiler/plugin.pb.cc
+++ b/src/google/protobuf/compiler/plugin.pb.cc
@@ -52,14 +52,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
CodeGeneratorRequest_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CodeGeneratorRequest_descriptor_,
- CodeGeneratorRequest::default_instance_,
+ CodeGeneratorRequest::internal_default_instance(),
CodeGeneratorRequest_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, _has_bits_),
-1,
-1,
sizeof(CodeGeneratorRequest),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorRequest, _internal_metadata_));
CodeGeneratorResponse_descriptor_ = file->message_type(1);
static const int CodeGeneratorResponse_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, error_),
@@ -68,14 +67,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
CodeGeneratorResponse_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CodeGeneratorResponse_descriptor_,
- CodeGeneratorResponse::default_instance_,
+ CodeGeneratorResponse::internal_default_instance(),
CodeGeneratorResponse_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, _has_bits_),
-1,
-1,
sizeof(CodeGeneratorResponse),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse, _internal_metadata_));
CodeGeneratorResponse_File_descriptor_ = CodeGeneratorResponse_descriptor_->nested_type(0);
static const int CodeGeneratorResponse_File_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, name_),
@@ -85,20 +83,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
CodeGeneratorResponse_File_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CodeGeneratorResponse_File_descriptor_,
- CodeGeneratorResponse_File::default_instance_,
+ CodeGeneratorResponse_File::internal_default_instance(),
CodeGeneratorResponse_File_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, _has_bits_),
-1,
-1,
sizeof(CodeGeneratorResponse_File),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CodeGeneratorResponse_File, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
}
@@ -107,32 +104,48 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- CodeGeneratorRequest_descriptor_, &CodeGeneratorRequest::default_instance());
+ CodeGeneratorRequest_descriptor_, CodeGeneratorRequest::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- CodeGeneratorResponse_descriptor_, &CodeGeneratorResponse::default_instance());
+ CodeGeneratorResponse_descriptor_, CodeGeneratorResponse::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- CodeGeneratorResponse_File_descriptor_, &CodeGeneratorResponse_File::default_instance());
+ CodeGeneratorResponse_File_descriptor_, CodeGeneratorResponse_File::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- delete CodeGeneratorRequest::default_instance_;
+ CodeGeneratorRequest_default_instance_.Shutdown();
delete CodeGeneratorRequest_reflection_;
- delete CodeGeneratorResponse::default_instance_;
+ CodeGeneratorResponse_default_instance_.Shutdown();
delete CodeGeneratorResponse_reflection_;
- delete CodeGeneratorResponse_File::default_instance_;
+ CodeGeneratorResponse_File_default_instance_.Shutdown();
delete CodeGeneratorResponse_File_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ ::google::protobuf::internal::GetEmptyString();
+ CodeGeneratorRequest_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ CodeGeneratorResponse_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ CodeGeneratorResponse_File_default_instance_.DefaultConstruct();
+ CodeGeneratorRequest_default_instance_.get_mutable()->InitAsDefaultInstance();
+ CodeGeneratorResponse_default_instance_.get_mutable()->InitAsDefaultInstance();
+ CodeGeneratorResponse_File_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n%google/protobuf/compiler/plugin.proto\022"
"\030google.protobuf.compiler\032 google/protob"
@@ -148,15 +161,15 @@ void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
"rotosZ\tplugin_go", 456);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/compiler/plugin.proto", &protobuf_RegisterTypes);
- CodeGeneratorRequest::default_instance_ = new CodeGeneratorRequest();
- CodeGeneratorResponse::default_instance_ = new CodeGeneratorResponse();
- CodeGeneratorResponse_File::default_instance_ = new CodeGeneratorResponse_File();
- CodeGeneratorRequest::default_instance_->InitAsDefaultInstance();
- CodeGeneratorResponse::default_instance_->InitAsDefaultInstance();
- CodeGeneratorResponse_File::default_instance_->InitAsDefaultInstance();
+ ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto() {
@@ -164,6 +177,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto
}
} static_descriptor_initializer_google_2fprotobuf_2fcompiler_2fplugin_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -174,6 +197,7 @@ const int CodeGeneratorRequest::kProtoFileFieldNumber;
CodeGeneratorRequest::CodeGeneratorRequest()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest)
}
@@ -185,15 +209,13 @@ CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorRequest)
}
void CodeGeneratorRequest::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CodeGeneratorRequest::~CodeGeneratorRequest() {
@@ -203,8 +225,6 @@ CodeGeneratorRequest::~CodeGeneratorRequest() {
void CodeGeneratorRequest::SharedDtor() {
parameter_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void CodeGeneratorRequest::SetCachedSize(int size) const {
@@ -218,11 +238,11 @@ const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() {
}
const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ return *internal_default_instance();
}
-CodeGeneratorRequest* CodeGeneratorRequest::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorRequest> CodeGeneratorRequest_default_instance_;
CodeGeneratorRequest* CodeGeneratorRequest::New(::google::protobuf::Arena* arena) const {
CodeGeneratorRequest* n = new CodeGeneratorRequest;
@@ -239,7 +259,7 @@ void CodeGeneratorRequest::Clear() {
}
file_to_generate_.Clear();
proto_file_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -368,6 +388,7 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
::google::protobuf::uint8* CodeGeneratorRequest::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorRequest)
// repeated string file_to_generate = 1;
for (int i = 0; i < this->file_to_generate_size(); i++) {
@@ -405,9 +426,9 @@ void CodeGeneratorRequest::SerializeWithCachedSizes(
return target;
}
-int CodeGeneratorRequest::ByteSize() const {
+size_t CodeGeneratorRequest::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.CodeGeneratorRequest)
- int total_size = 0;
+ size_t total_size = 0;
// optional string parameter = 2;
if (has_parameter()) {
@@ -417,18 +438,22 @@ int CodeGeneratorRequest::ByteSize() const {
}
// repeated string file_to_generate = 1;
- total_size += 1 * this->file_to_generate_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->file_to_generate_size());
for (int i = 0; i < this->file_to_generate_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->file_to_generate(i));
}
// repeated .google.protobuf.FileDescriptorProto proto_file = 15;
- total_size += 1 * this->proto_file_size();
- for (int i = 0; i < this->proto_file_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->proto_file(i));
+ {
+ unsigned int count = this->proto_file_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->proto_file(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -436,18 +461,17 @@ int CodeGeneratorRequest::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CodeGeneratorRequest::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const CodeGeneratorRequest* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const CodeGeneratorRequest* source =
::google::protobuf::internal::DynamicCastToGenerated<const CodeGeneratorRequest>(
&from);
if (source == NULL) {
@@ -455,16 +479,22 @@ void CodeGeneratorRequest::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorRequest)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
- file_to_generate_.MergeFrom(from.file_to_generate_);
+}
+
+void CodeGeneratorRequest::UnsafeMergeFrom(const CodeGeneratorRequest& from) {
+ GOOGLE_DCHECK(&from != this);
+ file_to_generate_.UnsafeMergeFrom(from.file_to_generate_);
proto_file_.MergeFrom(from.proto_file_);
if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) {
if (from.has_parameter()) {
@@ -473,7 +503,8 @@ void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -488,7 +519,7 @@ void CodeGeneratorRequest::CopyFrom(const CodeGeneratorRequest& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.CodeGeneratorRequest)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool CodeGeneratorRequest::IsInitialized() const {
@@ -528,49 +559,49 @@ int CodeGeneratorRequest::file_to_generate_size() const {
void CodeGeneratorRequest::clear_file_to_generate() {
file_to_generate_.Clear();
}
- const ::std::string& CodeGeneratorRequest::file_to_generate(int index) const {
+const ::std::string& CodeGeneratorRequest::file_to_generate(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
return file_to_generate_.Get(index);
}
- ::std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) {
+::std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
return file_to_generate_.Mutable(index);
}
- void CodeGeneratorRequest::set_file_to_generate(int index, const ::std::string& value) {
+void CodeGeneratorRequest::set_file_to_generate(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
file_to_generate_.Mutable(index)->assign(value);
}
- void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) {
+void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) {
file_to_generate_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
- void CodeGeneratorRequest::set_file_to_generate(int index, const char* value, size_t size) {
+void CodeGeneratorRequest::set_file_to_generate(int index, const char* value, size_t size) {
file_to_generate_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
- ::std::string* CodeGeneratorRequest::add_file_to_generate() {
+::std::string* CodeGeneratorRequest::add_file_to_generate() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
return file_to_generate_.Add();
}
- void CodeGeneratorRequest::add_file_to_generate(const ::std::string& value) {
+void CodeGeneratorRequest::add_file_to_generate(const ::std::string& value) {
file_to_generate_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
- void CodeGeneratorRequest::add_file_to_generate(const char* value) {
+void CodeGeneratorRequest::add_file_to_generate(const char* value) {
file_to_generate_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
- void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t size) {
+void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t size) {
file_to_generate_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
}
- const ::google::protobuf::RepeatedPtrField< ::std::string>&
+const ::google::protobuf::RepeatedPtrField< ::std::string>&
CodeGeneratorRequest::file_to_generate() const {
// @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
return file_to_generate_;
}
- ::google::protobuf::RepeatedPtrField< ::std::string>*
+::google::protobuf::RepeatedPtrField< ::std::string>*
CodeGeneratorRequest::mutable_file_to_generate() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate)
return &file_to_generate_;
@@ -590,37 +621,37 @@ void CodeGeneratorRequest::clear_parameter() {
parameter_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_parameter();
}
- const ::std::string& CodeGeneratorRequest::parameter() const {
+const ::std::string& CodeGeneratorRequest::parameter() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.parameter)
return parameter_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorRequest::set_parameter(const ::std::string& value) {
+void CodeGeneratorRequest::set_parameter(const ::std::string& value) {
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
- void CodeGeneratorRequest::set_parameter(const char* value) {
+void CodeGeneratorRequest::set_parameter(const char* value) {
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
- void CodeGeneratorRequest::set_parameter(const char* value, size_t size) {
+void CodeGeneratorRequest::set_parameter(const char* value, size_t size) {
set_has_parameter();
parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.parameter)
}
- ::std::string* CodeGeneratorRequest::mutable_parameter() {
+::std::string* CodeGeneratorRequest::mutable_parameter() {
set_has_parameter();
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.parameter)
return parameter_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* CodeGeneratorRequest::release_parameter() {
+::std::string* CodeGeneratorRequest::release_parameter() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter)
clear_has_parameter();
return parameter_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) {
+void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) {
if (parameter != NULL) {
set_has_parameter();
} else {
@@ -660,6 +691,9 @@ CodeGeneratorRequest::proto_file() const {
return proto_file_;
}
+inline const CodeGeneratorRequest* CodeGeneratorRequest::internal_default_instance() {
+ return &CodeGeneratorRequest_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -672,6 +706,7 @@ const int CodeGeneratorResponse_File::kContentFieldNumber;
CodeGeneratorResponse_File::CodeGeneratorResponse_File()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
}
@@ -683,17 +718,15 @@ CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorRespon
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse.File)
}
void CodeGeneratorResponse_File::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CodeGeneratorResponse_File::~CodeGeneratorResponse_File() {
@@ -705,8 +738,6 @@ void CodeGeneratorResponse_File::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
insertion_point_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
content_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void CodeGeneratorResponse_File::SetCachedSize(int size) const {
@@ -720,11 +751,11 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() {
}
const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ return *internal_default_instance();
}
-CodeGeneratorResponse_File* CodeGeneratorResponse_File::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse_File> CodeGeneratorResponse_File_default_instance_;
CodeGeneratorResponse_File* CodeGeneratorResponse_File::New(::google::protobuf::Arena* arena) const {
CodeGeneratorResponse_File* n = new CodeGeneratorResponse_File;
@@ -747,7 +778,7 @@ void CodeGeneratorResponse_File::Clear() {
content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
}
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -877,6 +908,7 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
::google::protobuf::uint8* CodeGeneratorResponse_File::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse.File)
// optional string name = 1;
if (has_name()) {
@@ -919,9 +951,9 @@ void CodeGeneratorResponse_File::SerializeWithCachedSizes(
return target;
}
-int CodeGeneratorResponse_File::ByteSize() const {
+size_t CodeGeneratorResponse_File::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.CodeGeneratorResponse.File)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 7u) {
// optional string name = 1;
@@ -951,18 +983,17 @@ int CodeGeneratorResponse_File::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CodeGeneratorResponse_File::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const CodeGeneratorResponse_File* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const CodeGeneratorResponse_File* source =
::google::protobuf::internal::DynamicCastToGenerated<const CodeGeneratorResponse_File>(
&from);
if (source == NULL) {
@@ -970,15 +1001,21 @@ void CodeGeneratorResponse_File::MergeFrom(const ::google::protobuf::Message& fr
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorResponse.File)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void CodeGeneratorResponse_File::UnsafeMergeFrom(const CodeGeneratorResponse_File& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_has_name();
@@ -994,7 +1031,8 @@ void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& fro
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -1009,7 +1047,7 @@ void CodeGeneratorResponse_File::CopyFrom(const CodeGeneratorResponse_File& from
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse.File)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool CodeGeneratorResponse_File::IsInitialized() const {
@@ -1048,6 +1086,7 @@ const int CodeGeneratorResponse::kFileFieldNumber;
CodeGeneratorResponse::CodeGeneratorResponse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse)
}
@@ -1059,15 +1098,13 @@ CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse)
}
void CodeGeneratorResponse::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
CodeGeneratorResponse::~CodeGeneratorResponse() {
@@ -1077,8 +1114,6 @@ CodeGeneratorResponse::~CodeGeneratorResponse() {
void CodeGeneratorResponse::SharedDtor() {
error_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void CodeGeneratorResponse::SetCachedSize(int size) const {
@@ -1092,11 +1127,11 @@ const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() {
}
const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ return *internal_default_instance();
}
-CodeGeneratorResponse* CodeGeneratorResponse::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse> CodeGeneratorResponse_default_instance_;
CodeGeneratorResponse* CodeGeneratorResponse::New(::google::protobuf::Arena* arena) const {
CodeGeneratorResponse* n = new CodeGeneratorResponse;
@@ -1112,7 +1147,7 @@ void CodeGeneratorResponse::Clear() {
error_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
file_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -1211,6 +1246,7 @@ void CodeGeneratorResponse::SerializeWithCachedSizes(
::google::protobuf::uint8* CodeGeneratorResponse::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse)
// optional string error = 1;
if (has_error()) {
@@ -1238,9 +1274,9 @@ void CodeGeneratorResponse::SerializeWithCachedSizes(
return target;
}
-int CodeGeneratorResponse::ByteSize() const {
+size_t CodeGeneratorResponse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.CodeGeneratorResponse)
- int total_size = 0;
+ size_t total_size = 0;
// optional string error = 1;
if (has_error()) {
@@ -1250,11 +1286,14 @@ int CodeGeneratorResponse::ByteSize() const {
}
// repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15;
- total_size += 1 * this->file_size();
- for (int i = 0; i < this->file_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->file(i));
+ {
+ unsigned int count = this->file_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->file(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -1262,18 +1301,17 @@ int CodeGeneratorResponse::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CodeGeneratorResponse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const CodeGeneratorResponse* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const CodeGeneratorResponse* source =
::google::protobuf::internal::DynamicCastToGenerated<const CodeGeneratorResponse>(
&from);
if (source == NULL) {
@@ -1281,15 +1319,21 @@ void CodeGeneratorResponse::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorResponse)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void CodeGeneratorResponse::UnsafeMergeFrom(const CodeGeneratorResponse& from) {
+ GOOGLE_DCHECK(&from != this);
file_.MergeFrom(from.file_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_error()) {
@@ -1298,7 +1342,8 @@ void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -1313,7 +1358,7 @@ void CodeGeneratorResponse::CopyFrom(const CodeGeneratorResponse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool CodeGeneratorResponse::IsInitialized() const {
@@ -1358,37 +1403,37 @@ void CodeGeneratorResponse_File::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& CodeGeneratorResponse_File::name() const {
+const ::std::string& CodeGeneratorResponse_File::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse_File::set_name(const ::std::string& value) {
+void CodeGeneratorResponse_File::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
- void CodeGeneratorResponse_File::set_name(const char* value) {
+void CodeGeneratorResponse_File::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
- void CodeGeneratorResponse_File::set_name(const char* value, size_t size) {
+void CodeGeneratorResponse_File::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.name)
}
- ::std::string* CodeGeneratorResponse_File::mutable_name() {
+::std::string* CodeGeneratorResponse_File::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* CodeGeneratorResponse_File::release_name() {
+::std::string* CodeGeneratorResponse_File::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) {
+void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -1412,37 +1457,37 @@ void CodeGeneratorResponse_File::clear_insertion_point() {
insertion_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_insertion_point();
}
- const ::std::string& CodeGeneratorResponse_File::insertion_point() const {
+const ::std::string& CodeGeneratorResponse_File::insertion_point() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
return insertion_point_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse_File::set_insertion_point(const ::std::string& value) {
+void CodeGeneratorResponse_File::set_insertion_point(const ::std::string& value) {
set_has_insertion_point();
insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
- void CodeGeneratorResponse_File::set_insertion_point(const char* value) {
+void CodeGeneratorResponse_File::set_insertion_point(const char* value) {
set_has_insertion_point();
insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
- void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) {
+void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) {
set_has_insertion_point();
insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
}
- ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() {
+::std::string* CodeGeneratorResponse_File::mutable_insertion_point() {
set_has_insertion_point();
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
return insertion_point_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* CodeGeneratorResponse_File::release_insertion_point() {
+::std::string* CodeGeneratorResponse_File::release_insertion_point() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point)
clear_has_insertion_point();
return insertion_point_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) {
+void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) {
if (insertion_point != NULL) {
set_has_insertion_point();
} else {
@@ -1466,37 +1511,37 @@ void CodeGeneratorResponse_File::clear_content() {
content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_content();
}
- const ::std::string& CodeGeneratorResponse_File::content() const {
+const ::std::string& CodeGeneratorResponse_File::content() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.content)
return content_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse_File::set_content(const ::std::string& value) {
+void CodeGeneratorResponse_File::set_content(const ::std::string& value) {
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
- void CodeGeneratorResponse_File::set_content(const char* value) {
+void CodeGeneratorResponse_File::set_content(const char* value) {
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
- void CodeGeneratorResponse_File::set_content(const char* value, size_t size) {
+void CodeGeneratorResponse_File::set_content(const char* value, size_t size) {
set_has_content();
content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
- ::std::string* CodeGeneratorResponse_File::mutable_content() {
+::std::string* CodeGeneratorResponse_File::mutable_content() {
set_has_content();
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.content)
return content_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* CodeGeneratorResponse_File::release_content() {
+::std::string* CodeGeneratorResponse_File::release_content() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content)
clear_has_content();
return content_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) {
+void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) {
if (content != NULL) {
set_has_content();
} else {
@@ -1506,6 +1551,9 @@ void CodeGeneratorResponse_File::clear_content() {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
+inline const CodeGeneratorResponse_File* CodeGeneratorResponse_File::internal_default_instance() {
+ return &CodeGeneratorResponse_File_default_instance_.get();
+}
// -------------------------------------------------------------------
// CodeGeneratorResponse
@@ -1524,37 +1572,37 @@ void CodeGeneratorResponse::clear_error() {
error_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_error();
}
- const ::std::string& CodeGeneratorResponse::error() const {
+const ::std::string& CodeGeneratorResponse::error() const {
// @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.error)
return error_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse::set_error(const ::std::string& value) {
+void CodeGeneratorResponse::set_error(const ::std::string& value) {
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.error)
}
- void CodeGeneratorResponse::set_error(const char* value) {
+void CodeGeneratorResponse::set_error(const char* value) {
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error)
}
- void CodeGeneratorResponse::set_error(const char* value, size_t size) {
+void CodeGeneratorResponse::set_error(const char* value, size_t size) {
set_has_error();
error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.error)
}
- ::std::string* CodeGeneratorResponse::mutable_error() {
+::std::string* CodeGeneratorResponse::mutable_error() {
set_has_error();
// @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.error)
return error_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* CodeGeneratorResponse::release_error() {
+::std::string* CodeGeneratorResponse::release_error() {
// @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error)
clear_has_error();
return error_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void CodeGeneratorResponse::set_allocated_error(::std::string* error) {
+void CodeGeneratorResponse::set_allocated_error(::std::string* error) {
if (error != NULL) {
set_has_error();
} else {
@@ -1594,6 +1642,9 @@ CodeGeneratorResponse::file() const {
return file_;
}
+inline const CodeGeneratorResponse* CodeGeneratorResponse::internal_default_instance() {
+ return &CodeGeneratorResponse_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h
index 13eeb69f..f9a99e75 100644
--- a/src/google/protobuf/compiler/plugin.pb.h
+++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -36,6 +36,7 @@ namespace compiler {
// Internal implementation detail -- do not call these.
void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
@@ -68,6 +69,8 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
static const ::google::protobuf::Descriptor* descriptor();
static const CodeGeneratorRequest& default_instance();
+ static const CodeGeneratorRequest* internal_default_instance();
+
void Swap(CodeGeneratorRequest* other);
// implements Message ----------------------------------------------
@@ -82,7 +85,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -98,6 +101,7 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CodeGeneratorRequest* other);
+ void UnsafeMergeFrom(const CodeGeneratorRequest& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -159,18 +163,20 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message
inline void clear_has_parameter();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_;
- ::google::protobuf::internal::ArenaStringPtr parameter_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_;
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::google::protobuf::internal::ArenaStringPtr parameter_;
+ friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
+ friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
void InitAsDefaultInstance();
- static CodeGeneratorRequest* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorRequest> CodeGeneratorRequest_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ {
@@ -196,6 +202,8 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
static const ::google::protobuf::Descriptor* descriptor();
static const CodeGeneratorResponse_File& default_instance();
+ static const CodeGeneratorResponse_File* internal_default_instance();
+
void Swap(CodeGeneratorResponse_File* other);
// implements Message ----------------------------------------------
@@ -210,7 +218,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -226,6 +234,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CodeGeneratorResponse_File* other);
+ void UnsafeMergeFrom(const CodeGeneratorResponse_File& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -287,18 +296,20 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M
inline void clear_has_content();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr insertion_point_;
::google::protobuf::internal::ArenaStringPtr content_;
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
+ friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
void InitAsDefaultInstance();
- static CodeGeneratorResponse_File* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse_File> CodeGeneratorResponse_File_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ {
@@ -324,6 +335,8 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
static const ::google::protobuf::Descriptor* descriptor();
static const CodeGeneratorResponse& default_instance();
+ static const CodeGeneratorResponse* internal_default_instance();
+
void Swap(CodeGeneratorResponse* other);
// implements Message ----------------------------------------------
@@ -338,7 +351,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -354,6 +367,7 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(CodeGeneratorResponse* other);
+ void UnsafeMergeFrom(const CodeGeneratorResponse& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -401,17 +415,19 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag
inline void clear_has_error();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
- ::google::protobuf::internal::ArenaStringPtr error_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_;
- friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
+ ::google::protobuf::internal::ArenaStringPtr error_;
+ friend void LIBPROTOC_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
+ friend void LIBPROTOC_EXPORT protobuf_AddDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fcompiler_2fplugin_2eproto();
void InitAsDefaultInstance();
- static CodeGeneratorResponse* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<CodeGeneratorResponse> CodeGeneratorResponse_default_instance_;
+
// ===================================================================
@@ -559,6 +575,9 @@ CodeGeneratorRequest::proto_file() const {
return proto_file_;
}
+inline const CodeGeneratorRequest* CodeGeneratorRequest::internal_default_instance() {
+ return &CodeGeneratorRequest_default_instance_.get();
+}
// -------------------------------------------------------------------
// CodeGeneratorResponse_File
@@ -725,6 +744,9 @@ inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* con
// @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content)
}
+inline const CodeGeneratorResponse_File* CodeGeneratorResponse_File::internal_default_instance() {
+ return &CodeGeneratorResponse_File_default_instance_.get();
+}
// -------------------------------------------------------------------
// CodeGeneratorResponse
@@ -813,6 +835,9 @@ CodeGeneratorResponse::file() const {
return file_;
}
+inline const CodeGeneratorResponse* CodeGeneratorResponse::internal_default_instance() {
+ return &CodeGeneratorResponse_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/python_generator.cc
index d5468a0c..3b1b0d1d 100644
--- a/src/google/protobuf/compiler/python/python_generator.cc
+++ b/src/google/protobuf/compiler/python/python_generator.cc
@@ -88,8 +88,8 @@ string StripProto(const string& filename) {
// Returns the Python module name expected for a given .proto filename.
string ModuleName(const string& filename) {
string basename = StripProto(filename);
- StripString(&basename, "-", '_');
- StripString(&basename, "/", '.');
+ ReplaceCharacters(&basename, "-", '_');
+ ReplaceCharacters(&basename, "/", '.');
return basename + "_pb2";
}
@@ -320,7 +320,7 @@ bool Generator::Generate(const FileDescriptor* file,
file_ = file;
string module_name = ModuleName(file->name());
string filename = module_name;
- StripString(&filename, ".", '/');
+ ReplaceCharacters(&filename, ".", '/');
filename += ".py";
FileDescriptorProto fdp;
@@ -430,6 +430,15 @@ void Generator::PrintFileDescriptor() const {
}
printer_->Print("]");
}
+ if (file_->public_dependency_count() > 0) {
+ printer_->Print(",\npublic_dependencies=[");
+ for (int i = 0; i < file_->public_dependency_count(); ++i) {
+ string module_alias = ModuleAlias(file_->public_dependency(i)->name());
+ printer_->Print("$module_alias$.DESCRIPTOR,", "module_alias",
+ module_alias);
+ }
+ printer_->Print("]");
+ }
// TODO(falk): Also print options and fix the message_type, enum_type,
// service and extension later in the generation.
@@ -1094,6 +1103,8 @@ void Generator::PrintFieldDescriptor(
m["default_value"] = StringifyDefaultValue(field);
m["is_extension"] = is_extension ? "True" : "False";
m["options"] = OptionsValue("FieldOptions", 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
// these fields in correctly after all referenced descriptors have been
// defined and/or imported (see FixForeignFieldsInDescriptors()).
@@ -1104,7 +1115,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$)";
+ " options=$options$$json_name$)";
printer_->Print(m, field_descriptor_decl);
}
diff --git a/src/google/protobuf/compiler/ruby/ruby_generator.h b/src/google/protobuf/compiler/ruby/ruby_generator.h
index 75555c31..8c1dfa26 100644
--- a/src/google/protobuf/compiler/ruby/ruby_generator.h
+++ b/src/google/protobuf/compiler/ruby/ruby_generator.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Generates Ruby code for a given .proto file.
+
#ifndef GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__
#define GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__
@@ -40,6 +42,10 @@ namespace protobuf {
namespace compiler {
namespace ruby {
+// CodeGenerator implementation for generated Ruby protocol buffer classes.
+// If you create your own protocol compiler binary and you want it to support
+// Ruby output, you can do so by registering an instance of this
+// CodeGenerator with the CommandLineInterface in your main() function.
class LIBPROTOC_EXPORT Generator
: public google::protobuf::compiler::CodeGenerator {
virtual bool Generate(
diff --git a/src/google/protobuf/compiler/subprocess.cc b/src/google/protobuf/compiler/subprocess.cc
index 6e258664..e929e4fb 100644
--- a/src/google/protobuf/compiler/subprocess.cc
+++ b/src/google/protobuf/compiler/subprocess.cc
@@ -261,12 +261,12 @@ string Subprocess::Win32ErrorMessage(DWORD error_code) {
char* message;
// WTF?
- FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, error_code, 0,
- (LPTSTR)&message, // NOT A BUG!
- 0, NULL);
+ FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, error_code, 0,
+ (LPSTR)&message, // NOT A BUG!
+ 0, NULL);
string result = message;
LocalFree(message);
diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc
index 9b20946c..be1e1d69 100644
--- a/src/google/protobuf/descriptor.cc
+++ b/src/google/protobuf/descriptor.cc
@@ -69,6 +69,7 @@
#undef PACKAGE // autoheader #defines this. :(
namespace google {
+
namespace protobuf {
const FieldDescriptor::CppType
@@ -164,6 +165,15 @@ const int FieldDescriptor::kLastReservedNumber;
namespace {
+// Note: I distrust ctype.h due to locales.
+char ToUpper(char ch) {
+ return (ch >= 'a' && ch <= 'z') ? (ch - 'a' + 'A') : ch;
+}
+
+char ToLower(char ch) {
+ return (ch >= 'A' && ch <= 'Z') ? (ch - 'A' + 'a') : ch;
+}
+
string ToCamelCase(const string& input, bool lower_first) {
bool capitalize_next = !lower_first;
string result;
@@ -173,12 +183,7 @@ string ToCamelCase(const string& input, bool lower_first) {
if (input[i] == '_') {
capitalize_next = true;
} else if (capitalize_next) {
- // Note: I distrust ctype.h due to locales.
- if ('a' <= input[i] && input[i] <= 'z') {
- result.push_back(input[i] - 'a' + 'A');
- } else {
- result.push_back(input[i]);
- }
+ result.push_back(ToUpper(input[i]));
capitalize_next = false;
} else {
result.push_back(input[i]);
@@ -186,13 +191,116 @@ string ToCamelCase(const string& input, bool lower_first) {
}
// Lower-case the first letter.
- if (lower_first && !result.empty() && 'A' <= result[0] && result[0] <= 'Z') {
- result[0] = result[0] - 'A' + 'a';
+ if (lower_first && !result.empty()) {
+ result[0] = ToLower(result[0]);
}
return result;
}
+string ToJsonName(const string& input) {
+ bool capitalize_next = false;
+ string result;
+ result.reserve(input.size());
+
+ for (int i = 0; i < input.size(); i++) {
+ if (input[i] == '_') {
+ capitalize_next = true;
+ } else if (capitalize_next) {
+ result.push_back(ToUpper(input[i]));
+ capitalize_next = false;
+ } else {
+ result.push_back(input[i]);
+ }
+ }
+
+ return result;
+}
+
+string EnumValueToPascalCase(const string& input) {
+ bool next_upper = true;
+ string result;
+ result.reserve(input.size());
+
+ for (int i = 0; i < input.size(); i++) {
+ if (input[i] == '_') {
+ next_upper = true;
+ } else {
+ if (next_upper) {
+ result.push_back(ToUpper(input[i]));
+ } else {
+ result.push_back(ToLower(input[i]));
+ }
+ next_upper = false;
+ }
+ }
+
+ return result;
+}
+
+// Class to remove an enum prefix from enum values.
+class PrefixRemover {
+ public:
+ PrefixRemover(StringPiece prefix) {
+ // Strip underscores and lower-case the prefix.
+ for (int i = 0; i < prefix.size(); i++) {
+ if (prefix[i] != '_') {
+ prefix_ += ascii_tolower(prefix[i]);
+ }
+ }
+ }
+
+ // Tries to remove the enum prefix from this enum value.
+ // If this is not possible, returns the input verbatim.
+ string MaybeRemove(StringPiece str) {
+ // We can't just lowercase and strip str and look for a prefix.
+ // We need to properly recognize the difference between:
+ //
+ // enum Foo {
+ // FOO_BAR_BAZ = 0;
+ // FOO_BARBAZ = 1;
+ // }
+ //
+ // This is acceptable (though perhaps not advisable) because even when
+ // we PascalCase, these two will still be distinct (BarBaz vs. Barbaz).
+ size_t i, j;
+
+ // Skip past prefix_ in str if we can.
+ for (i = 0, j = 0; i < str.size() && j < prefix_.size(); i++) {
+ if (str[i] == '_') {
+ continue;
+ }
+
+ if (ascii_tolower(str[i]) != prefix_[j++]) {
+ return str.as_string();
+ }
+ }
+
+ // If we didn't make it through the prefix, we've failed to strip the
+ // prefix.
+ if (j < prefix_.size()) {
+ return str.as_string();
+ }
+
+ // Skip underscores between prefix and further characters.
+ while (i < str.size() && str[i] == '_') {
+ i++;
+ }
+
+ // Enum label can't be the empty string.
+ if (i == str.size()) {
+ return str.as_string();
+ }
+
+ // We successfully stripped the prefix.
+ str.remove_prefix(i);
+ return str.as_string();
+ }
+
+ private:
+ string prefix_;
+};
+
// 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
@@ -2390,6 +2498,17 @@ void FieldDescriptor::DebugString(int depth,
strings::SubstituteAndAppend(contents, " [default = $0",
DefaultValueAsString(true));
}
+ if (has_json_name_) {
+ if (!bracketed) {
+ bracketed = true;
+ contents->append("[");
+ } else {
+ contents->append(", ");
+ }
+ contents->append("json_name = \"");
+ contents->append(CEscape(json_name()));
+ contents->append("\"");
+ }
string formatted_options;
if (FormatBracketedOptions(depth, options(), &formatted_options)) {
@@ -2980,6 +3099,8 @@ class DescriptorBuilder {
void BuildOneof(const OneofDescriptorProto& proto,
Descriptor* parent,
OneofDescriptor* result);
+ void CheckEnumValueUniqueness(const EnumDescriptorProto& proto,
+ const EnumDescriptor* result);
void BuildEnum(const EnumDescriptorProto& proto,
const Descriptor* parent,
EnumDescriptor* result);
@@ -4232,7 +4353,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
result->json_name_ = tables_->AllocateString(proto.json_name());
} else {
result->has_json_name_ = false;
- result->json_name_ = result->camelcase_name_;
+ result->json_name_ = tables_->AllocateString(ToJsonName(proto.name()));
}
// Some compilers do not allow static_cast directly between two enum types,
@@ -4540,6 +4661,70 @@ void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto,
proto, Symbol(result));
}
+void DescriptorBuilder::CheckEnumValueUniqueness(
+ const EnumDescriptorProto& proto, const EnumDescriptor* result) {
+
+ // Check that enum labels are still unique when we remove the enum prefix from
+ // values that have it.
+ //
+ // This will fail for something like:
+ //
+ // enum MyEnum {
+ // MY_ENUM_FOO = 0;
+ // FOO = 1;
+ // }
+ //
+ // By enforcing this reasonable constraint, we allow code generators to strip
+ // the prefix and/or PascalCase it without creating conflicts. This can lead
+ // to much nicer language-specific enums like:
+ //
+ // enum NameType {
+ // FirstName = 1,
+ // LastName = 2,
+ // }
+ //
+ // Instead of:
+ //
+ // enum NameType {
+ // NAME_TYPE_FIRST_NAME = 1,
+ // NAME_TYPE_LAST_NAME = 2,
+ // }
+ PrefixRemover remover(result->name());
+ map<string, const google::protobuf::EnumValueDescriptor*> values;
+ for (int i = 0; i < result->value_count(); i++) {
+ const google::protobuf::EnumValueDescriptor* value = result->value(i);
+ string stripped =
+ EnumValueToPascalCase(remover.MaybeRemove(value->name()));
+ std::pair<map<string, const google::protobuf::EnumValueDescriptor*>::iterator, bool>
+ insert_result = values.insert(std::make_pair(stripped, value));
+ bool inserted = insert_result.second;
+
+ // We don't throw the error if the two conflicting symbols are identical, or
+ // if they map to the same number. In the former case, the normal symbol
+ // duplication error will fire so we don't need to (and its error message
+ // will make more sense). We allow the latter case so users can create
+ // aliases which add or remove the prefix (code generators that do prefix
+ // stripping should de-dup the labels in this case).
+ if (!inserted && insert_result.first->second->name() != value->name() &&
+ insert_result.first->second->number() != value->number()) {
+ string error_message =
+ "When enum name is stripped and label is PascalCased (" + stripped +
+ "), this value label conflicts with " + values[stripped]->name() +
+ ". This will make the proto fail to compile for some languages, such "
+ "as C#.";
+ // There are proto2 enums out there with conflicting names, so to preserve
+ // compatibility we issue only a warning for proto2.
+ if (result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2) {
+ AddWarning(value->full_name(), proto.value(i),
+ DescriptorPool::ErrorCollector::NAME, error_message);
+ } else {
+ AddError(value->full_name(), proto.value(i),
+ DescriptorPool::ErrorCollector::NAME, error_message);
+ }
+ }
+ }
+}
+
void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
const Descriptor* parent,
EnumDescriptor* result) {
@@ -4568,6 +4753,8 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
BUILD_ARRAY(proto, result, value, BuildEnumValue, result);
+ CheckEnumValueUniqueness(proto, result);
+
// Copy options.
if (!proto.has_options()) {
result->options_ = NULL; // Will set to default_instance later.
@@ -5254,7 +5441,6 @@ void DescriptorBuilder::ValidateProto3Enum(
}
}
-
void DescriptorBuilder::ValidateMessageOptions(Descriptor* message,
const DescriptorProto& proto) {
VALIDATE_OPTIONS_FROM_ARRAY(message, field, Field);
@@ -5275,7 +5461,6 @@ void DescriptorBuilder::ValidateMessageOptions(Descriptor* message,
max_extension_range));
}
}
-
}
void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field,
diff --git a/src/google/protobuf/descriptor.h b/src/google/protobuf/descriptor.h
index b040b62c..0151e1d9 100644
--- a/src/google/protobuf/descriptor.h
+++ b/src/google/protobuf/descriptor.h
@@ -143,7 +143,7 @@ struct SourceLocation {
// See the comments in SourceCodeInfo.Location (descriptor.proto) for details.
string leading_comments;
string trailing_comments;
- vector<string> leading_detached_comments;
+ std::vector<string> leading_detached_comments;
};
// Options when generating machine-parsable output from a descriptor with
@@ -558,6 +558,10 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// Does this field have an explicitly-declared default value?
bool has_default_value() const;
+ // Whether the user has specified the json_name field option in the .proto
+ // file.
+ bool has_json_name() const;
+
// Get the field default value if cpp_type() == CPPTYPE_INT32. If no
// explicit default was defined, the default is 0.
int32 default_value_int32() const;
@@ -683,7 +687,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor {
// file.
bool has_json_name_;
// If has_json_name_ is true, it's the value specified by the user.
- // Otherwise, it has the same value as lowercase_name_.
+ // Otherwise, it has the same value as camelcase_name_.
const string* json_name_;
const FileDescriptor* file_;
int number_;
@@ -1699,6 +1703,7 @@ PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, message_type, const Descriptor*)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, enum_type, const EnumDescriptor*)
PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool)
+PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool)
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32 , int32 )
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64 , int64 )
PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32, uint32)
diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc
index 0028c708..1e21e230 100644
--- a/src/google/protobuf/descriptor.pb.cc
+++ b/src/google/protobuf/descriptor.pb.cc
@@ -120,14 +120,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
FileDescriptorSet_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FileDescriptorSet_descriptor_,
- FileDescriptorSet::default_instance_,
+ FileDescriptorSet::internal_default_instance(),
FileDescriptorSet_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _has_bits_),
-1,
-1,
sizeof(FileDescriptorSet),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _internal_metadata_));
FileDescriptorProto_descriptor_ = file->message_type(1);
static const int FileDescriptorProto_offsets_[12] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, name_),
@@ -146,14 +145,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
FileDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FileDescriptorProto_descriptor_,
- FileDescriptorProto::default_instance_,
+ FileDescriptorProto::internal_default_instance(),
FileDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _has_bits_),
-1,
-1,
sizeof(FileDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _internal_metadata_));
DescriptorProto_descriptor_ = file->message_type(2);
static const int DescriptorProto_offsets_[10] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, name_),
@@ -170,14 +168,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
DescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
DescriptorProto_descriptor_,
- DescriptorProto::default_instance_,
+ DescriptorProto::internal_default_instance(),
DescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _has_bits_),
-1,
-1,
sizeof(DescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _internal_metadata_));
DescriptorProto_ExtensionRange_descriptor_ = DescriptorProto_descriptor_->nested_type(0);
static const int DescriptorProto_ExtensionRange_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, start_),
@@ -186,14 +183,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
DescriptorProto_ExtensionRange_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
DescriptorProto_ExtensionRange_descriptor_,
- DescriptorProto_ExtensionRange::default_instance_,
+ DescriptorProto_ExtensionRange::internal_default_instance(),
DescriptorProto_ExtensionRange_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _has_bits_),
-1,
-1,
sizeof(DescriptorProto_ExtensionRange),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _internal_metadata_));
DescriptorProto_ReservedRange_descriptor_ = DescriptorProto_descriptor_->nested_type(1);
static const int DescriptorProto_ReservedRange_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, start_),
@@ -202,14 +198,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
DescriptorProto_ReservedRange_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
DescriptorProto_ReservedRange_descriptor_,
- DescriptorProto_ReservedRange::default_instance_,
+ DescriptorProto_ReservedRange::internal_default_instance(),
DescriptorProto_ReservedRange_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, _has_bits_),
-1,
-1,
sizeof(DescriptorProto_ReservedRange),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ReservedRange, _internal_metadata_));
FieldDescriptorProto_descriptor_ = file->message_type(3);
static const int FieldDescriptorProto_offsets_[10] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, name_),
@@ -226,14 +221,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
FieldDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FieldDescriptorProto_descriptor_,
- FieldDescriptorProto::default_instance_,
+ FieldDescriptorProto::internal_default_instance(),
FieldDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _has_bits_),
-1,
-1,
sizeof(FieldDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _internal_metadata_));
FieldDescriptorProto_Type_descriptor_ = FieldDescriptorProto_descriptor_->enum_type(0);
FieldDescriptorProto_Label_descriptor_ = FieldDescriptorProto_descriptor_->enum_type(1);
OneofDescriptorProto_descriptor_ = file->message_type(4);
@@ -244,14 +238,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
OneofDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
OneofDescriptorProto_descriptor_,
- OneofDescriptorProto::default_instance_,
+ OneofDescriptorProto::internal_default_instance(),
OneofDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, _has_bits_),
-1,
-1,
sizeof(OneofDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofDescriptorProto, _internal_metadata_));
EnumDescriptorProto_descriptor_ = file->message_type(5);
static const int EnumDescriptorProto_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, name_),
@@ -261,14 +254,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
EnumDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
EnumDescriptorProto_descriptor_,
- EnumDescriptorProto::default_instance_,
+ EnumDescriptorProto::internal_default_instance(),
EnumDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _has_bits_),
-1,
-1,
sizeof(EnumDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _internal_metadata_));
EnumValueDescriptorProto_descriptor_ = file->message_type(6);
static const int EnumValueDescriptorProto_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, name_),
@@ -278,14 +270,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
EnumValueDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
EnumValueDescriptorProto_descriptor_,
- EnumValueDescriptorProto::default_instance_,
+ EnumValueDescriptorProto::internal_default_instance(),
EnumValueDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _has_bits_),
-1,
-1,
sizeof(EnumValueDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _internal_metadata_));
ServiceDescriptorProto_descriptor_ = file->message_type(7);
static const int ServiceDescriptorProto_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, name_),
@@ -295,14 +286,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
ServiceDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
ServiceDescriptorProto_descriptor_,
- ServiceDescriptorProto::default_instance_,
+ ServiceDescriptorProto::internal_default_instance(),
ServiceDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _has_bits_),
-1,
-1,
sizeof(ServiceDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _internal_metadata_));
MethodDescriptorProto_descriptor_ = file->message_type(8);
static const int MethodDescriptorProto_offsets_[6] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, name_),
@@ -315,14 +305,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
MethodDescriptorProto_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MethodDescriptorProto_descriptor_,
- MethodDescriptorProto::default_instance_,
+ MethodDescriptorProto::internal_default_instance(),
MethodDescriptorProto_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _has_bits_),
-1,
-1,
sizeof(MethodDescriptorProto),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _internal_metadata_));
FileOptions_descriptor_ = file->message_type(9);
static const int FileOptions_offsets_[15] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_package_),
@@ -344,14 +333,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
FileOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FileOptions_descriptor_,
- FileOptions::default_instance_,
+ FileOptions::internal_default_instance(),
FileOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _extensions_),
sizeof(FileOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _internal_metadata_));
FileOptions_OptimizeMode_descriptor_ = FileOptions_descriptor_->enum_type(0);
MessageOptions_descriptor_ = file->message_type(10);
static const int MessageOptions_offsets_[5] = {
@@ -364,14 +352,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
MessageOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MessageOptions_descriptor_,
- MessageOptions::default_instance_,
+ MessageOptions::internal_default_instance(),
MessageOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _extensions_),
sizeof(MessageOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _internal_metadata_));
FieldOptions_descriptor_ = file->message_type(11);
static const int FieldOptions_offsets_[7] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, ctype_),
@@ -385,14 +372,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
FieldOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FieldOptions_descriptor_,
- FieldOptions::default_instance_,
+ FieldOptions::internal_default_instance(),
FieldOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _extensions_),
sizeof(FieldOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _internal_metadata_));
FieldOptions_CType_descriptor_ = FieldOptions_descriptor_->enum_type(0);
FieldOptions_JSType_descriptor_ = FieldOptions_descriptor_->enum_type(1);
OneofOptions_descriptor_ = file->message_type(12);
@@ -402,14 +388,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
OneofOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
OneofOptions_descriptor_,
- OneofOptions::default_instance_,
+ OneofOptions::internal_default_instance(),
OneofOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _extensions_),
sizeof(OneofOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(OneofOptions, _internal_metadata_));
EnumOptions_descriptor_ = file->message_type(13);
static const int EnumOptions_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, allow_alias_),
@@ -419,14 +404,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
EnumOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
EnumOptions_descriptor_,
- EnumOptions::default_instance_,
+ EnumOptions::internal_default_instance(),
EnumOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _extensions_),
sizeof(EnumOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _internal_metadata_));
EnumValueOptions_descriptor_ = file->message_type(14);
static const int EnumValueOptions_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, deprecated_),
@@ -435,14 +419,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
EnumValueOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
EnumValueOptions_descriptor_,
- EnumValueOptions::default_instance_,
+ EnumValueOptions::internal_default_instance(),
EnumValueOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _extensions_),
sizeof(EnumValueOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _internal_metadata_));
ServiceOptions_descriptor_ = file->message_type(15);
static const int ServiceOptions_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, deprecated_),
@@ -451,14 +434,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
ServiceOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
ServiceOptions_descriptor_,
- ServiceOptions::default_instance_,
+ ServiceOptions::internal_default_instance(),
ServiceOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _extensions_),
sizeof(ServiceOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _internal_metadata_));
MethodOptions_descriptor_ = file->message_type(16);
static const int MethodOptions_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, deprecated_),
@@ -467,14 +449,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
MethodOptions_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MethodOptions_descriptor_,
- MethodOptions::default_instance_,
+ MethodOptions::internal_default_instance(),
MethodOptions_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _has_bits_),
-1,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _extensions_),
sizeof(MethodOptions),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _internal_metadata_));
UninterpretedOption_descriptor_ = file->message_type(17);
static const int UninterpretedOption_offsets_[7] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, name_),
@@ -488,14 +469,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
UninterpretedOption_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
UninterpretedOption_descriptor_,
- UninterpretedOption::default_instance_,
+ UninterpretedOption::internal_default_instance(),
UninterpretedOption_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _has_bits_),
-1,
-1,
sizeof(UninterpretedOption),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _internal_metadata_));
UninterpretedOption_NamePart_descriptor_ = UninterpretedOption_descriptor_->nested_type(0);
static const int UninterpretedOption_NamePart_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, name_part_),
@@ -504,14 +484,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
UninterpretedOption_NamePart_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
UninterpretedOption_NamePart_descriptor_,
- UninterpretedOption_NamePart::default_instance_,
+ UninterpretedOption_NamePart::internal_default_instance(),
UninterpretedOption_NamePart_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _has_bits_),
-1,
-1,
sizeof(UninterpretedOption_NamePart),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _internal_metadata_));
SourceCodeInfo_descriptor_ = file->message_type(18);
static const int SourceCodeInfo_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, location_),
@@ -519,14 +498,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
SourceCodeInfo_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
SourceCodeInfo_descriptor_,
- SourceCodeInfo::default_instance_,
+ SourceCodeInfo::internal_default_instance(),
SourceCodeInfo_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, _has_bits_),
-1,
-1,
sizeof(SourceCodeInfo),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo, _internal_metadata_));
SourceCodeInfo_Location_descriptor_ = SourceCodeInfo_descriptor_->nested_type(0);
static const int SourceCodeInfo_Location_offsets_[5] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, path_),
@@ -538,14 +516,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
SourceCodeInfo_Location_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
SourceCodeInfo_Location_descriptor_,
- SourceCodeInfo_Location::default_instance_,
+ SourceCodeInfo_Location::internal_default_instance(),
SourceCodeInfo_Location_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, _has_bits_),
-1,
-1,
sizeof(SourceCodeInfo_Location),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceCodeInfo_Location, _internal_metadata_));
GeneratedCodeInfo_descriptor_ = file->message_type(19);
static const int GeneratedCodeInfo_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, annotation_),
@@ -553,14 +530,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
GeneratedCodeInfo_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
GeneratedCodeInfo_descriptor_,
- GeneratedCodeInfo::default_instance_,
+ GeneratedCodeInfo::internal_default_instance(),
GeneratedCodeInfo_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, _has_bits_),
-1,
-1,
sizeof(GeneratedCodeInfo),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo, _internal_metadata_));
GeneratedCodeInfo_Annotation_descriptor_ = GeneratedCodeInfo_descriptor_->nested_type(0);
static const int GeneratedCodeInfo_Annotation_offsets_[4] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, path_),
@@ -571,20 +547,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() {
GeneratedCodeInfo_Annotation_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
GeneratedCodeInfo_Annotation_descriptor_,
- GeneratedCodeInfo_Annotation::default_instance_,
+ GeneratedCodeInfo_Annotation::internal_default_instance(),
GeneratedCodeInfo_Annotation_offsets_,
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _has_bits_),
-1,
-1,
sizeof(GeneratedCodeInfo_Annotation),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _internal_metadata_),
- -1);
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto);
}
@@ -593,119 +568,189 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FileDescriptorSet_descriptor_, &FileDescriptorSet::default_instance());
+ FileDescriptorSet_descriptor_, FileDescriptorSet::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FileDescriptorProto_descriptor_, &FileDescriptorProto::default_instance());
+ FileDescriptorProto_descriptor_, FileDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- DescriptorProto_descriptor_, &DescriptorProto::default_instance());
+ DescriptorProto_descriptor_, DescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- DescriptorProto_ExtensionRange_descriptor_, &DescriptorProto_ExtensionRange::default_instance());
+ DescriptorProto_ExtensionRange_descriptor_, DescriptorProto_ExtensionRange::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- DescriptorProto_ReservedRange_descriptor_, &DescriptorProto_ReservedRange::default_instance());
+ DescriptorProto_ReservedRange_descriptor_, DescriptorProto_ReservedRange::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FieldDescriptorProto_descriptor_, &FieldDescriptorProto::default_instance());
+ FieldDescriptorProto_descriptor_, FieldDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- OneofDescriptorProto_descriptor_, &OneofDescriptorProto::default_instance());
+ OneofDescriptorProto_descriptor_, OneofDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- EnumDescriptorProto_descriptor_, &EnumDescriptorProto::default_instance());
+ EnumDescriptorProto_descriptor_, EnumDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- EnumValueDescriptorProto_descriptor_, &EnumValueDescriptorProto::default_instance());
+ EnumValueDescriptorProto_descriptor_, EnumValueDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- ServiceDescriptorProto_descriptor_, &ServiceDescriptorProto::default_instance());
+ ServiceDescriptorProto_descriptor_, ServiceDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- MethodDescriptorProto_descriptor_, &MethodDescriptorProto::default_instance());
+ MethodDescriptorProto_descriptor_, MethodDescriptorProto::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FileOptions_descriptor_, &FileOptions::default_instance());
+ FileOptions_descriptor_, FileOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- MessageOptions_descriptor_, &MessageOptions::default_instance());
+ MessageOptions_descriptor_, MessageOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FieldOptions_descriptor_, &FieldOptions::default_instance());
+ FieldOptions_descriptor_, FieldOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- OneofOptions_descriptor_, &OneofOptions::default_instance());
+ OneofOptions_descriptor_, OneofOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- EnumOptions_descriptor_, &EnumOptions::default_instance());
+ EnumOptions_descriptor_, EnumOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- EnumValueOptions_descriptor_, &EnumValueOptions::default_instance());
+ EnumValueOptions_descriptor_, EnumValueOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- ServiceOptions_descriptor_, &ServiceOptions::default_instance());
+ ServiceOptions_descriptor_, ServiceOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- MethodOptions_descriptor_, &MethodOptions::default_instance());
+ MethodOptions_descriptor_, MethodOptions::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- UninterpretedOption_descriptor_, &UninterpretedOption::default_instance());
+ UninterpretedOption_descriptor_, UninterpretedOption::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- UninterpretedOption_NamePart_descriptor_, &UninterpretedOption_NamePart::default_instance());
+ UninterpretedOption_NamePart_descriptor_, UninterpretedOption_NamePart::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- SourceCodeInfo_descriptor_, &SourceCodeInfo::default_instance());
+ SourceCodeInfo_descriptor_, SourceCodeInfo::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- SourceCodeInfo_Location_descriptor_, &SourceCodeInfo_Location::default_instance());
+ SourceCodeInfo_Location_descriptor_, SourceCodeInfo_Location::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- GeneratedCodeInfo_descriptor_, &GeneratedCodeInfo::default_instance());
+ GeneratedCodeInfo_descriptor_, GeneratedCodeInfo::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- GeneratedCodeInfo_Annotation_descriptor_, &GeneratedCodeInfo_Annotation::default_instance());
+ GeneratedCodeInfo_Annotation_descriptor_, GeneratedCodeInfo_Annotation::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto() {
- delete FileDescriptorSet::default_instance_;
+ FileDescriptorSet_default_instance_.Shutdown();
delete FileDescriptorSet_reflection_;
- delete FileDescriptorProto::default_instance_;
+ FileDescriptorProto_default_instance_.Shutdown();
delete FileDescriptorProto_reflection_;
- delete DescriptorProto::default_instance_;
+ DescriptorProto_default_instance_.Shutdown();
delete DescriptorProto_reflection_;
- delete DescriptorProto_ExtensionRange::default_instance_;
+ DescriptorProto_ExtensionRange_default_instance_.Shutdown();
delete DescriptorProto_ExtensionRange_reflection_;
- delete DescriptorProto_ReservedRange::default_instance_;
+ DescriptorProto_ReservedRange_default_instance_.Shutdown();
delete DescriptorProto_ReservedRange_reflection_;
- delete FieldDescriptorProto::default_instance_;
+ FieldDescriptorProto_default_instance_.Shutdown();
delete FieldDescriptorProto_reflection_;
- delete OneofDescriptorProto::default_instance_;
+ OneofDescriptorProto_default_instance_.Shutdown();
delete OneofDescriptorProto_reflection_;
- delete EnumDescriptorProto::default_instance_;
+ EnumDescriptorProto_default_instance_.Shutdown();
delete EnumDescriptorProto_reflection_;
- delete EnumValueDescriptorProto::default_instance_;
+ EnumValueDescriptorProto_default_instance_.Shutdown();
delete EnumValueDescriptorProto_reflection_;
- delete ServiceDescriptorProto::default_instance_;
+ ServiceDescriptorProto_default_instance_.Shutdown();
delete ServiceDescriptorProto_reflection_;
- delete MethodDescriptorProto::default_instance_;
+ MethodDescriptorProto_default_instance_.Shutdown();
delete MethodDescriptorProto_reflection_;
- delete FileOptions::default_instance_;
+ FileOptions_default_instance_.Shutdown();
delete FileOptions_reflection_;
- delete MessageOptions::default_instance_;
+ MessageOptions_default_instance_.Shutdown();
delete MessageOptions_reflection_;
- delete FieldOptions::default_instance_;
+ FieldOptions_default_instance_.Shutdown();
delete FieldOptions_reflection_;
- delete OneofOptions::default_instance_;
+ OneofOptions_default_instance_.Shutdown();
delete OneofOptions_reflection_;
- delete EnumOptions::default_instance_;
+ EnumOptions_default_instance_.Shutdown();
delete EnumOptions_reflection_;
- delete EnumValueOptions::default_instance_;
+ EnumValueOptions_default_instance_.Shutdown();
delete EnumValueOptions_reflection_;
- delete ServiceOptions::default_instance_;
+ ServiceOptions_default_instance_.Shutdown();
delete ServiceOptions_reflection_;
- delete MethodOptions::default_instance_;
+ MethodOptions_default_instance_.Shutdown();
delete MethodOptions_reflection_;
- delete UninterpretedOption::default_instance_;
+ UninterpretedOption_default_instance_.Shutdown();
delete UninterpretedOption_reflection_;
- delete UninterpretedOption_NamePart::default_instance_;
+ UninterpretedOption_NamePart_default_instance_.Shutdown();
delete UninterpretedOption_NamePart_reflection_;
- delete SourceCodeInfo::default_instance_;
+ SourceCodeInfo_default_instance_.Shutdown();
delete SourceCodeInfo_reflection_;
- delete SourceCodeInfo_Location::default_instance_;
+ SourceCodeInfo_Location_default_instance_.Shutdown();
delete SourceCodeInfo_Location_reflection_;
- delete GeneratedCodeInfo::default_instance_;
+ GeneratedCodeInfo_default_instance_.Shutdown();
delete GeneratedCodeInfo_reflection_;
- delete GeneratedCodeInfo_Annotation::default_instance_;
+ GeneratedCodeInfo_Annotation_default_instance_.Shutdown();
delete GeneratedCodeInfo_Annotation_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ FileDescriptorSet_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ FileDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ DescriptorProto_default_instance_.DefaultConstruct();
+ DescriptorProto_ExtensionRange_default_instance_.DefaultConstruct();
+ DescriptorProto_ReservedRange_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ FieldDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ OneofDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ EnumDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ EnumValueDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ ServiceDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ MethodDescriptorProto_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ FileOptions_default_instance_.DefaultConstruct();
+ MessageOptions_default_instance_.DefaultConstruct();
+ FieldOptions_default_instance_.DefaultConstruct();
+ OneofOptions_default_instance_.DefaultConstruct();
+ EnumOptions_default_instance_.DefaultConstruct();
+ EnumValueOptions_default_instance_.DefaultConstruct();
+ ServiceOptions_default_instance_.DefaultConstruct();
+ MethodOptions_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ UninterpretedOption_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ UninterpretedOption_NamePart_default_instance_.DefaultConstruct();
+ SourceCodeInfo_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ SourceCodeInfo_Location_default_instance_.DefaultConstruct();
+ GeneratedCodeInfo_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ GeneratedCodeInfo_Annotation_default_instance_.DefaultConstruct();
+ FileDescriptorSet_default_instance_.get_mutable()->InitAsDefaultInstance();
+ FileDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ DescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ DescriptorProto_ExtensionRange_default_instance_.get_mutable()->InitAsDefaultInstance();
+ DescriptorProto_ReservedRange_default_instance_.get_mutable()->InitAsDefaultInstance();
+ FieldDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ OneofDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ EnumDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ EnumValueDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ ServiceDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ MethodDescriptorProto_default_instance_.get_mutable()->InitAsDefaultInstance();
+ FileOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ MessageOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ FieldOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ OneofOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ EnumOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ EnumValueOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ ServiceOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ MethodOptions_default_instance_.get_mutable()->InitAsDefaultInstance();
+ UninterpretedOption_default_instance_.get_mutable()->InitAsDefaultInstance();
+ UninterpretedOption_NamePart_default_instance_.get_mutable()->InitAsDefaultInstance();
+ SourceCodeInfo_default_instance_.get_mutable()->InitAsDefaultInstance();
+ SourceCodeInfo_Location_default_instance_.get_mutable()->InitAsDefaultInstance();
+ GeneratedCodeInfo_default_instance_.get_mutable()->InitAsDefaultInstance();
+ GeneratedCodeInfo_Annotation_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n google/protobuf/descriptor.proto\022\017goog"
"le.protobuf\"G\n\021FileDescriptorSet\0222\n\004file"
@@ -772,129 +817,84 @@ void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() {
"\n\013output_type\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.g"
"oogle.protobuf.MethodOptions\022\037\n\020client_s"
"treaming\030\005 \001(\010:\005false\022\037\n\020server_streamin"
- "g\030\006 \001(\010:\005false\"\207\005\n\013FileOptions\022\024\n\014java_p"
+ "g\030\006 \001(\010:\005false\"\204\005\n\013FileOptions\022\024\n\014java_p"
"ackage\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 \001"
- "(\t\022\"\n\023java_multiple_files\030\n \001(\010:\005false\022,"
- "\n\035java_generate_equals_and_hash\030\024 \001(\010:\005f"
- "alse\022%\n\026java_string_check_utf8\030\033 \001(\010:\005fa"
- "lse\022F\n\014optimize_for\030\t \001(\0162).google.proto"
- "buf.FileOptions.OptimizeMode:\005SPEED\022\022\n\ng"
- "o_package\030\013 \001(\t\022\"\n\023cc_generic_services\030\020"
- " \001(\010:\005false\022$\n\025java_generic_services\030\021 \001"
- "(\010:\005false\022\"\n\023py_generic_services\030\022 \001(\010:\005"
- "false\022\031\n\ndeprecated\030\027 \001(\010:\005false\022\037\n\020cc_e"
- "nable_arenas\030\037 \001(\010:\005false\022\031\n\021objc_class_"
- "prefix\030$ \001(\t\022\030\n\020csharp_namespace\030% \001(\t\022C"
- "\n\024uninterpreted_option\030\347\007 \003(\0132$.google.p"
- "rotobuf.UninterpretedOption\":\n\014OptimizeM"
- "ode\022\t\n\005SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RU"
- "NTIME\020\003*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\346\001\n\016MessageOpti"
- "ons\022&\n\027message_set_wire_format\030\001 \001(\010:\005fa"
- "lse\022.\n\037no_standard_descriptor_accessor\030\002"
- " \001(\010:\005false\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021"
- "\n\tmap_entry\030\007 \001(\010\022C\n\024uninterpreted_optio"
- "n\030\347\007 \003(\0132$.google.protobuf.Uninterpreted"
- "Option*\t\010\350\007\020\200\200\200\200\002\"\230\003\n\014FieldOptions\022:\n\005ct"
- "ype\030\001 \001(\0162#.google.protobuf.FieldOptions"
- ".CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006jstype"
- "\030\006 \001(\0162$.google.protobuf.FieldOptions.JS"
- "Type:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005false\022\031\n\n"
- "deprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001(\010:\005f"
- "alse\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.go"
- "ogle.protobuf.UninterpretedOption\"/\n\005CTy"
- "pe\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_PIECE"
- "\020\002\"5\n\006JSType\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_STRING"
- "\020\001\022\r\n\tJS_NUMBER\020\002*\t\010\350\007\020\200\200\200\200\002\"^\n\014OneofOpt"
- "ions\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.go"
- "ogle.protobuf.UninterpretedOption*\t\010\350\007\020\200"
- "\200\200\200\002\"\215\001\n\013EnumOptions\022\023\n\013allow_alias\030\002 \001("
- "\010\022\031\n\ndeprecated\030\003 \001(\010:\005false\022C\n\024uninterp"
- "reted_option\030\347\007 \003(\0132$.google.protobuf.Un"
- "interpretedOption*\t\010\350\007\020\200\200\200\200\002\"}\n\020EnumValu"
- "eOptions\022\031\n\ndeprecated\030\001 \001(\010:\005false\022C\n\024u"
+ "(\t\022\"\n\023java_multiple_files\030\n \001(\010:\005false\022)"
+ "\n\035java_generate_equals_and_hash\030\024 \001(\010B\002\030"
+ "\001\022%\n\026java_string_check_utf8\030\033 \001(\010:\005false"
+ "\022F\n\014optimize_for\030\t \001(\0162).google.protobuf"
+ ".FileOptions.OptimizeMode:\005SPEED\022\022\n\ngo_p"
+ "ackage\030\013 \001(\t\022\"\n\023cc_generic_services\030\020 \001("
+ "\010:\005false\022$\n\025java_generic_services\030\021 \001(\010:"
+ "\005false\022\"\n\023py_generic_services\030\022 \001(\010:\005fal"
+ "se\022\031\n\ndeprecated\030\027 \001(\010:\005false\022\037\n\020cc_enab"
+ "le_arenas\030\037 \001(\010:\005false\022\031\n\021objc_class_pre"
+ "fix\030$ \001(\t\022\030\n\020csharp_namespace\030% \001(\t\022C\n\024u"
"ninterpreted_option\030\347\007 \003(\0132$.google.prot"
- "obuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"{\n\016S"
- "erviceOptions\022\031\n\ndeprecated\030! \001(\010:\005false"
- "\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.google"
- ".protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002"
- "\"z\n\rMethodOptions\022\031\n\ndeprecated\030! \001(\010:\005f"
+ "obuf.UninterpretedOption\":\n\014OptimizeMode"
+ "\022\t\n\005SPEED\020\001\022\r\n\tCODE_SIZE\020\002\022\020\n\014LITE_RUNTI"
+ "ME\020\003*\t\010\350\007\020\200\200\200\200\002J\004\010&\020\'\"\354\001\n\016MessageOptions"
+ "\022&\n\027message_set_wire_format\030\001 \001(\010:\005false"
+ "\022.\n\037no_standard_descriptor_accessor\030\002 \001("
+ "\010:\005false\022\031\n\ndeprecated\030\003 \001(\010:\005false\022\021\n\tm"
+ "ap_entry\030\007 \001(\010\022C\n\024uninterpreted_option\030\347"
+ "\007 \003(\0132$.google.protobuf.UninterpretedOpt"
+ "ion*\t\010\350\007\020\200\200\200\200\002J\004\010\010\020\t\"\236\003\n\014FieldOptions\022:\n"
+ "\005ctype\030\001 \001(\0162#.google.protobuf.FieldOpti"
+ "ons.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\?\n\006jst"
+ "ype\030\006 \001(\0162$.google.protobuf.FieldOptions"
+ ".JSType:\tJS_NORMAL\022\023\n\004lazy\030\005 \001(\010:\005false\022"
+ "\031\n\ndeprecated\030\003 \001(\010:\005false\022\023\n\004weak\030\n \001(\010"
+ ":\005false\022C\n\024uninterpreted_option\030\347\007 \003(\0132$"
+ ".google.protobuf.UninterpretedOption\"/\n\005"
+ "CType\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014STRING_PI"
+ "ECE\020\002\"5\n\006JSType\022\r\n\tJS_NORMAL\020\000\022\r\n\tJS_STR"
+ "ING\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.UninterpretedOpti"
+ "on*\t\010\350\007\020\200\200\200\200\002\"\215\001\n\013EnumOptions\022\023\n\013allow_a"
+ "lias\030\002 \001(\010\022\031\n\ndeprecated\030\003 \001(\010:\005false\022C\n"
+ "\024uninterpreted_option\030\347\007 \003(\0132$.google.pr"
+ "otobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"}\n"
+ "\020EnumValueOptions\022\031\n\ndeprecated\030\001 \001(\010:\005f"
"alse\022C\n\024uninterpreted_option\030\347\007 \003(\0132$.go"
"ogle.protobuf.UninterpretedOption*\t\010\350\007\020\200"
- "\200\200\200\002\"\236\002\n\023UninterpretedOption\022;\n\004name\030\002 \003"
- "(\0132-.google.protobuf.UninterpretedOption"
- ".NamePart\022\030\n\020identifier_value\030\003 \001(\t\022\032\n\022p"
- "ositive_int_value\030\004 \001(\004\022\032\n\022negative_int_"
- "value\030\005 \001(\003\022\024\n\014double_value\030\006 \001(\001\022\024\n\014str"
- "ing_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_ex"
- "tension\030\002 \002(\010\"\325\001\n\016SourceCodeInfo\022:\n\010loca"
- "tion\030\001 \003(\0132(.google.protobuf.SourceCodeI"
- "nfo.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_comment"
- "s\030\003 \001(\t\022\031\n\021trailing_comments\030\004 \001(\t\022!\n\031le"
- "ading_detached_comments\030\006 \003(\t\"\247\001\n\021Genera"
- "tedCodeInfo\022A\n\nannotation\030\001 \003(\0132-.google"
- ".protobuf.GeneratedCodeInfo.Annotation\032O"
- "\n\nAnnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022\023\n\013source"
- "_file\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003end\030\004 \001(\005B"
- "[\n\023com.google.protobufB\020DescriptorProtos"
- "H\001Z\ndescriptor\240\001\001\242\002\003GPB\252\002\032Google.Protobu"
- "f.Reflection", 5292);
+ "\200\200\200\002\"{\n\016ServiceOptions\022\031\n\ndeprecated\030! \001"
+ "(\010:\005false\022C\n\024uninterpreted_option\030\347\007 \003(\013"
+ "2$.google.protobuf.UninterpretedOption*\t"
+ "\010\350\007\020\200\200\200\200\002\"z\n\rMethodOptions\022\031\n\ndeprecated"
+ "\030! \001(\010:\005false\022C\n\024uninterpreted_option\030\347\007"
+ " \003(\0132$.google.protobuf.UninterpretedOpti"
+ "on*\t\010\350\007\020\200\200\200\200\002\"\236\002\n\023UninterpretedOption\022;\n"
+ "\004name\030\002 \003(\0132-.google.protobuf.Uninterpre"
+ "tedOption.NamePart\022\030\n\020identifier_value\030\003"
+ " \001(\t\022\032\n\022positive_int_value\030\004 \001(\004\022\032\n\022nega"
+ "tive_int_value\030\005 \001(\003\022\024\n\014double_value\030\006 \001"
+ "(\001\022\024\n\014string_value\030\007 \001(\014\022\027\n\017aggregate_va"
+ "lue\030\010 \001(\t\0323\n\010NamePart\022\021\n\tname_part\030\001 \002(\t"
+ "\022\024\n\014is_extension\030\002 \002(\010\"\325\001\n\016SourceCodeInf"
+ "o\022:\n\010location\030\001 \003(\0132(.google.protobuf.So"
+ "urceCodeInfo.Location\032\206\001\n\010Location\022\020\n\004pa"
+ "th\030\001 \003(\005B\002\020\001\022\020\n\004span\030\002 \003(\005B\002\020\001\022\030\n\020leadin"
+ "g_comments\030\003 \001(\t\022\031\n\021trailing_comments\030\004 "
+ "\001(\t\022!\n\031leading_detached_comments\030\006 \003(\t\"\247"
+ "\001\n\021GeneratedCodeInfo\022A\n\nannotation\030\001 \003(\013"
+ "2-.google.protobuf.GeneratedCodeInfo.Ann"
+ "otation\032O\n\nAnnotation\022\020\n\004path\030\001 \003(\005B\002\020\001\022"
+ "\023\n\013source_file\030\002 \001(\t\022\r\n\005begin\030\003 \001(\005\022\013\n\003e"
+ "nd\030\004 \001(\005BX\n\023com.google.protobufB\020Descrip"
+ "torProtosH\001Z\ndescriptor\242\002\003GPB\252\002\032Google.P"
+ "rotobuf.Reflection", 5298);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/descriptor.proto", &protobuf_RegisterTypes);
- FileDescriptorSet::default_instance_ = new FileDescriptorSet();
- FileDescriptorProto::default_instance_ = new FileDescriptorProto();
- DescriptorProto::default_instance_ = new DescriptorProto();
- DescriptorProto_ExtensionRange::default_instance_ = new DescriptorProto_ExtensionRange();
- DescriptorProto_ReservedRange::default_instance_ = new DescriptorProto_ReservedRange();
- FieldDescriptorProto::default_instance_ = new FieldDescriptorProto();
- OneofDescriptorProto::default_instance_ = new OneofDescriptorProto();
- EnumDescriptorProto::default_instance_ = new EnumDescriptorProto();
- EnumValueDescriptorProto::default_instance_ = new EnumValueDescriptorProto();
- ServiceDescriptorProto::default_instance_ = new ServiceDescriptorProto();
- MethodDescriptorProto::default_instance_ = new MethodDescriptorProto();
- FileOptions::default_instance_ = new FileOptions();
- MessageOptions::default_instance_ = new MessageOptions();
- FieldOptions::default_instance_ = new FieldOptions();
- OneofOptions::default_instance_ = new OneofOptions();
- EnumOptions::default_instance_ = new EnumOptions();
- EnumValueOptions::default_instance_ = new EnumValueOptions();
- ServiceOptions::default_instance_ = new ServiceOptions();
- MethodOptions::default_instance_ = new MethodOptions();
- UninterpretedOption::default_instance_ = new UninterpretedOption();
- UninterpretedOption_NamePart::default_instance_ = new UninterpretedOption_NamePart();
- SourceCodeInfo::default_instance_ = new SourceCodeInfo();
- SourceCodeInfo_Location::default_instance_ = new SourceCodeInfo_Location();
- GeneratedCodeInfo::default_instance_ = new GeneratedCodeInfo();
- GeneratedCodeInfo_Annotation::default_instance_ = new GeneratedCodeInfo_Annotation();
- FileDescriptorSet::default_instance_->InitAsDefaultInstance();
- FileDescriptorProto::default_instance_->InitAsDefaultInstance();
- DescriptorProto::default_instance_->InitAsDefaultInstance();
- DescriptorProto_ExtensionRange::default_instance_->InitAsDefaultInstance();
- DescriptorProto_ReservedRange::default_instance_->InitAsDefaultInstance();
- FieldDescriptorProto::default_instance_->InitAsDefaultInstance();
- OneofDescriptorProto::default_instance_->InitAsDefaultInstance();
- EnumDescriptorProto::default_instance_->InitAsDefaultInstance();
- EnumValueDescriptorProto::default_instance_->InitAsDefaultInstance();
- ServiceDescriptorProto::default_instance_->InitAsDefaultInstance();
- MethodDescriptorProto::default_instance_->InitAsDefaultInstance();
- FileOptions::default_instance_->InitAsDefaultInstance();
- MessageOptions::default_instance_->InitAsDefaultInstance();
- FieldOptions::default_instance_->InitAsDefaultInstance();
- OneofOptions::default_instance_->InitAsDefaultInstance();
- EnumOptions::default_instance_->InitAsDefaultInstance();
- EnumValueOptions::default_instance_->InitAsDefaultInstance();
- ServiceOptions::default_instance_->InitAsDefaultInstance();
- MethodOptions::default_instance_->InitAsDefaultInstance();
- UninterpretedOption::default_instance_->InitAsDefaultInstance();
- UninterpretedOption_NamePart::default_instance_->InitAsDefaultInstance();
- SourceCodeInfo::default_instance_->InitAsDefaultInstance();
- SourceCodeInfo_Location::default_instance_->InitAsDefaultInstance();
- GeneratedCodeInfo::default_instance_->InitAsDefaultInstance();
- GeneratedCodeInfo_Annotation::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto() {
@@ -902,6 +902,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2fdescriptor_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -910,6 +920,7 @@ const int FileDescriptorSet::kFileFieldNumber;
FileDescriptorSet::FileDescriptorSet()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorSet)
}
@@ -921,13 +932,12 @@ FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet)
}
void FileDescriptorSet::SharedCtor() {
_cached_size_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
FileDescriptorSet::~FileDescriptorSet() {
@@ -936,8 +946,6 @@ FileDescriptorSet::~FileDescriptorSet() {
}
void FileDescriptorSet::SharedDtor() {
- if (this != default_instance_) {
- }
}
void FileDescriptorSet::SetCachedSize(int size) const {
@@ -951,11 +959,11 @@ const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() {
}
const FileDescriptorSet& FileDescriptorSet::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-FileDescriptorSet* FileDescriptorSet::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorSet> FileDescriptorSet_default_instance_;
FileDescriptorSet* FileDescriptorSet::New(::google::protobuf::Arena* arena) const {
FileDescriptorSet* n = new FileDescriptorSet;
@@ -968,7 +976,7 @@ FileDescriptorSet* FileDescriptorSet::New(::google::protobuf::Arena* arena) cons
void FileDescriptorSet::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FileDescriptorSet)
file_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -1040,6 +1048,7 @@ void FileDescriptorSet::SerializeWithCachedSizes(
::google::protobuf::uint8* FileDescriptorSet::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileDescriptorSet)
// repeated .google.protobuf.FileDescriptorProto file = 1;
for (unsigned int i = 0, n = this->file_size(); i < n; i++) {
@@ -1056,16 +1065,19 @@ void FileDescriptorSet::SerializeWithCachedSizes(
return target;
}
-int FileDescriptorSet::ByteSize() const {
+size_t FileDescriptorSet::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FileDescriptorSet)
- int total_size = 0;
+ size_t total_size = 0;
// repeated .google.protobuf.FileDescriptorProto file = 1;
- total_size += 1 * this->file_size();
- for (int i = 0; i < this->file_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->file(i));
+ {
+ unsigned int count = this->file_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->file(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -1073,18 +1085,17 @@ int FileDescriptorSet::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FileDescriptorSet::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileDescriptorSet)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FileDescriptorSet* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FileDescriptorSet* source =
::google::protobuf::internal::DynamicCastToGenerated<const FileDescriptorSet>(
&from);
if (source == NULL) {
@@ -1092,18 +1103,25 @@ void FileDescriptorSet::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FileDescriptorSet)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FileDescriptorSet::MergeFrom(const FileDescriptorSet& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorSet)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void FileDescriptorSet::UnsafeMergeFrom(const FileDescriptorSet& from) {
+ GOOGLE_DCHECK(&from != this);
file_.MergeFrom(from.file_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -1118,7 +1136,7 @@ void FileDescriptorSet::CopyFrom(const FileDescriptorSet& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FileDescriptorSet)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FileDescriptorSet::IsInitialized() const {
@@ -1179,6 +1197,9 @@ FileDescriptorSet::file() const {
return file_;
}
+inline const FileDescriptorSet* FileDescriptorSet::internal_default_instance() {
+ return &FileDescriptorSet_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1200,32 +1221,33 @@ const int FileDescriptorProto::kSyntaxFieldNumber;
FileDescriptorProto::FileDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileDescriptorProto)
}
void FileDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::FileOptions*>(&::google::protobuf::FileOptions::default_instance());
- source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>(&::google::protobuf::SourceCodeInfo::default_instance());
+ options_ = const_cast< ::google::protobuf::FileOptions*>(
+ ::google::protobuf::FileOptions::internal_default_instance());
+ source_code_info_ = const_cast< ::google::protobuf::SourceCodeInfo*>(
+ ::google::protobuf::SourceCodeInfo::internal_default_instance());
}
FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorProto)
}
void FileDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
source_code_info_ = NULL;
- syntax_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
FileDescriptorProto::~FileDescriptorProto() {
@@ -1237,7 +1259,7 @@ void FileDescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
syntax_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &FileDescriptorProto_default_instance_.get()) {
delete options_;
delete source_code_info_;
}
@@ -1254,11 +1276,11 @@ const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() {
}
const FileDescriptorProto& FileDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-FileDescriptorProto* FileDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorProto> FileDescriptorProto_default_instance_;
FileDescriptorProto* FileDescriptorProto::New(::google::protobuf::Arena* arena) const {
FileDescriptorProto* n = new FileDescriptorProto;
@@ -1296,7 +1318,7 @@ void FileDescriptorProto::Clear() {
enum_type_.Clear();
service_.Clear();
extension_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -1632,6 +1654,7 @@ void FileDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* FileDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -1738,9 +1761,9 @@ void FileDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int FileDescriptorProto::ByteSize() const {
+size_t FileDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FileDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 3u) {
// optional string name = 1;
@@ -1782,7 +1805,8 @@ int FileDescriptorProto::ByteSize() const {
}
// repeated string dependency = 3;
- total_size += 1 * this->dependency_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->dependency_size());
for (int i = 0; i < this->dependency_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->dependency(i));
@@ -1790,54 +1814,72 @@ int FileDescriptorProto::ByteSize() const {
// repeated int32 public_dependency = 10;
{
- int data_size = 0;
- for (int i = 0; i < this->public_dependency_size(); i++) {
+ size_t data_size = 0;
+ unsigned int count = this->public_dependency_size();
+ for (unsigned int i = 0; i < count; i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int32Size(this->public_dependency(i));
}
- total_size += 1 * this->public_dependency_size() + data_size;
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->public_dependency_size());
+ total_size += data_size;
}
// repeated int32 weak_dependency = 11;
{
- int data_size = 0;
- for (int i = 0; i < this->weak_dependency_size(); i++) {
+ size_t data_size = 0;
+ unsigned int count = this->weak_dependency_size();
+ for (unsigned int i = 0; i < count; i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int32Size(this->weak_dependency(i));
}
- total_size += 1 * this->weak_dependency_size() + data_size;
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->weak_dependency_size());
+ total_size += data_size;
}
// repeated .google.protobuf.DescriptorProto message_type = 4;
- total_size += 1 * this->message_type_size();
- for (int i = 0; i < this->message_type_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->message_type(i));
+ {
+ unsigned int count = this->message_type_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->message_type(i));
+ }
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 5;
- total_size += 1 * this->enum_type_size();
- for (int i = 0; i < this->enum_type_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->enum_type(i));
+ {
+ unsigned int count = this->enum_type_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->enum_type(i));
+ }
}
// repeated .google.protobuf.ServiceDescriptorProto service = 6;
- total_size += 1 * this->service_size();
- for (int i = 0; i < this->service_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->service(i));
+ {
+ unsigned int count = this->service_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->service(i));
+ }
}
// repeated .google.protobuf.FieldDescriptorProto extension = 7;
- total_size += 1 * this->extension_size();
- for (int i = 0; i < this->extension_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->extension(i));
+ {
+ unsigned int count = this->extension_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->extension(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -1845,18 +1887,17 @@ int FileDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FileDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FileDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FileDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const FileDescriptorProto>(
&from);
if (source == NULL) {
@@ -1864,18 +1905,24 @@ void FileDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FileDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
- dependency_.MergeFrom(from.dependency_);
- public_dependency_.MergeFrom(from.public_dependency_);
- weak_dependency_.MergeFrom(from.weak_dependency_);
+}
+
+void FileDescriptorProto::UnsafeMergeFrom(const FileDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
+ dependency_.UnsafeMergeFrom(from.dependency_);
+ public_dependency_.UnsafeMergeFrom(from.public_dependency_);
+ weak_dependency_.UnsafeMergeFrom(from.weak_dependency_);
message_type_.MergeFrom(from.message_type_);
enum_type_.MergeFrom(from.enum_type_);
service_.MergeFrom(from.service_);
@@ -1903,7 +1950,8 @@ void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -1918,7 +1966,7 @@ void FileDescriptorProto::CopyFrom(const FileDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FileDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FileDescriptorProto::IsInitialized() const {
@@ -1980,37 +2028,37 @@ void FileDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& FileDescriptorProto::name() const {
+const ::std::string& FileDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileDescriptorProto::set_name(const ::std::string& value) {
+void FileDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.name)
}
- void FileDescriptorProto::set_name(const char* value) {
+void FileDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.name)
}
- void FileDescriptorProto::set_name(const char* value, size_t size) {
+void FileDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.name)
}
- ::std::string* FileDescriptorProto::mutable_name() {
+::std::string* FileDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileDescriptorProto::release_name() {
+::std::string* FileDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileDescriptorProto::set_allocated_name(::std::string* name) {
+void FileDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -2034,37 +2082,37 @@ void FileDescriptorProto::clear_package() {
package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_package();
}
- const ::std::string& FileDescriptorProto::package() const {
+const ::std::string& FileDescriptorProto::package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.package)
return package_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileDescriptorProto::set_package(const ::std::string& value) {
+void FileDescriptorProto::set_package(const ::std::string& value) {
set_has_package();
package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.package)
}
- void FileDescriptorProto::set_package(const char* value) {
+void FileDescriptorProto::set_package(const char* value) {
set_has_package();
package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.package)
}
- void FileDescriptorProto::set_package(const char* value, size_t size) {
+void FileDescriptorProto::set_package(const char* value, size_t size) {
set_has_package();
package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.package)
}
- ::std::string* FileDescriptorProto::mutable_package() {
+::std::string* FileDescriptorProto::mutable_package() {
set_has_package();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.package)
return package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileDescriptorProto::release_package() {
+::std::string* FileDescriptorProto::release_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package)
clear_has_package();
return package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileDescriptorProto::set_allocated_package(::std::string* package) {
+void FileDescriptorProto::set_allocated_package(::std::string* package) {
if (package != NULL) {
set_has_package();
} else {
@@ -2081,49 +2129,49 @@ int FileDescriptorProto::dependency_size() const {
void FileDescriptorProto::clear_dependency() {
dependency_.Clear();
}
- const ::std::string& FileDescriptorProto::dependency(int index) const {
+const ::std::string& FileDescriptorProto::dependency(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.dependency)
return dependency_.Get(index);
}
- ::std::string* FileDescriptorProto::mutable_dependency(int index) {
+::std::string* FileDescriptorProto::mutable_dependency(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.dependency)
return dependency_.Mutable(index);
}
- void FileDescriptorProto::set_dependency(int index, const ::std::string& value) {
+void FileDescriptorProto::set_dependency(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency)
dependency_.Mutable(index)->assign(value);
}
- void FileDescriptorProto::set_dependency(int index, const char* value) {
+void FileDescriptorProto::set_dependency(int index, const char* value) {
dependency_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.dependency)
}
- void FileDescriptorProto::set_dependency(int index, const char* value, size_t size) {
+void FileDescriptorProto::set_dependency(int index, const char* value, size_t size) {
dependency_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.dependency)
}
- ::std::string* FileDescriptorProto::add_dependency() {
+::std::string* FileDescriptorProto::add_dependency() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.FileDescriptorProto.dependency)
return dependency_.Add();
}
- void FileDescriptorProto::add_dependency(const ::std::string& value) {
+void FileDescriptorProto::add_dependency(const ::std::string& value) {
dependency_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency)
}
- void FileDescriptorProto::add_dependency(const char* value) {
+void FileDescriptorProto::add_dependency(const char* value) {
dependency_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.FileDescriptorProto.dependency)
}
- void FileDescriptorProto::add_dependency(const char* value, size_t size) {
+void FileDescriptorProto::add_dependency(const char* value, size_t size) {
dependency_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.FileDescriptorProto.dependency)
}
- const ::google::protobuf::RepeatedPtrField< ::std::string>&
+const ::google::protobuf::RepeatedPtrField< ::std::string>&
FileDescriptorProto::dependency() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.dependency)
return dependency_;
}
- ::google::protobuf::RepeatedPtrField< ::std::string>*
+::google::protobuf::RepeatedPtrField< ::std::string>*
FileDescriptorProto::mutable_dependency() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.dependency)
return &dependency_;
@@ -2136,24 +2184,24 @@ int FileDescriptorProto::public_dependency_size() const {
void FileDescriptorProto::clear_public_dependency() {
public_dependency_.Clear();
}
- ::google::protobuf::int32 FileDescriptorProto::public_dependency(int index) const {
+::google::protobuf::int32 FileDescriptorProto::public_dependency(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.public_dependency)
return public_dependency_.Get(index);
}
- void FileDescriptorProto::set_public_dependency(int index, ::google::protobuf::int32 value) {
+void FileDescriptorProto::set_public_dependency(int index, ::google::protobuf::int32 value) {
public_dependency_.Set(index, value);
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.public_dependency)
}
- void FileDescriptorProto::add_public_dependency(::google::protobuf::int32 value) {
+void FileDescriptorProto::add_public_dependency(::google::protobuf::int32 value) {
public_dependency_.Add(value);
// @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.public_dependency)
}
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
FileDescriptorProto::public_dependency() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.public_dependency)
return public_dependency_;
}
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
FileDescriptorProto::mutable_public_dependency() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.public_dependency)
return &public_dependency_;
@@ -2166,24 +2214,24 @@ int FileDescriptorProto::weak_dependency_size() const {
void FileDescriptorProto::clear_weak_dependency() {
weak_dependency_.Clear();
}
- ::google::protobuf::int32 FileDescriptorProto::weak_dependency(int index) const {
+::google::protobuf::int32 FileDescriptorProto::weak_dependency(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.weak_dependency)
return weak_dependency_.Get(index);
}
- void FileDescriptorProto::set_weak_dependency(int index, ::google::protobuf::int32 value) {
+void FileDescriptorProto::set_weak_dependency(int index, ::google::protobuf::int32 value) {
weak_dependency_.Set(index, value);
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.weak_dependency)
}
- void FileDescriptorProto::add_weak_dependency(::google::protobuf::int32 value) {
+void FileDescriptorProto::add_weak_dependency(::google::protobuf::int32 value) {
weak_dependency_.Add(value);
// @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.weak_dependency)
}
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
FileDescriptorProto::weak_dependency() const {
// @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.weak_dependency)
return weak_dependency_;
}
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
FileDescriptorProto::mutable_weak_dependency() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.weak_dependency)
return &weak_dependency_;
@@ -2325,7 +2373,8 @@ void FileDescriptorProto::clear_options() {
}
const ::google::protobuf::FileOptions& FileDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::FileOptions::internal_default_instance();
}
::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
set_has_options();
@@ -2369,7 +2418,8 @@ void FileDescriptorProto::clear_source_code_info() {
}
const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info)
- return source_code_info_ != NULL ? *source_code_info_ : *default_instance_->source_code_info_;
+ return source_code_info_ != NULL ? *source_code_info_
+ : *::google::protobuf::SourceCodeInfo::internal_default_instance();
}
::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() {
set_has_source_code_info();
@@ -2411,37 +2461,37 @@ void FileDescriptorProto::clear_syntax() {
syntax_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_syntax();
}
- const ::std::string& FileDescriptorProto::syntax() const {
+const ::std::string& FileDescriptorProto::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.syntax)
return syntax_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileDescriptorProto::set_syntax(const ::std::string& value) {
+void FileDescriptorProto::set_syntax(const ::std::string& value) {
set_has_syntax();
syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.syntax)
}
- void FileDescriptorProto::set_syntax(const char* value) {
+void FileDescriptorProto::set_syntax(const char* value) {
set_has_syntax();
syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.syntax)
}
- void FileDescriptorProto::set_syntax(const char* value, size_t size) {
+void FileDescriptorProto::set_syntax(const char* value, size_t size) {
set_has_syntax();
syntax_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.syntax)
}
- ::std::string* FileDescriptorProto::mutable_syntax() {
+::std::string* FileDescriptorProto::mutable_syntax() {
set_has_syntax();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.syntax)
return syntax_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileDescriptorProto::release_syntax() {
+::std::string* FileDescriptorProto::release_syntax() {
// @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax)
clear_has_syntax();
return syntax_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
+void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
if (syntax != NULL) {
set_has_syntax();
} else {
@@ -2451,6 +2501,9 @@ void FileDescriptorProto::clear_syntax() {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax)
}
+inline const FileDescriptorProto* FileDescriptorProto::internal_default_instance() {
+ return &FileDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -2462,6 +2515,7 @@ const int DescriptorProto_ExtensionRange::kEndFieldNumber;
DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ExtensionRange)
}
@@ -2473,15 +2527,14 @@ DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorP
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ExtensionRange)
}
void DescriptorProto_ExtensionRange::SharedCtor() {
_cached_size_ = 0;
- start_ = 0;
- end_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&start_, 0, reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_) + sizeof(end_));
}
DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() {
@@ -2490,8 +2543,6 @@ DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() {
}
void DescriptorProto_ExtensionRange::SharedDtor() {
- if (this != default_instance_) {
- }
}
void DescriptorProto_ExtensionRange::SetCachedSize(int size) const {
@@ -2505,11 +2556,11 @@ const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor
}
const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ExtensionRange> DescriptorProto_ExtensionRange_default_instance_;
DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::New(::google::protobuf::Arena* arena) const {
DescriptorProto_ExtensionRange* n = new DescriptorProto_ExtensionRange;
@@ -2533,7 +2584,7 @@ void DescriptorProto_ExtensionRange::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -2542,7 +2593,7 @@ void DescriptorProto_ExtensionRange::Clear() {
#undef ZR_HELPER_
#undef ZR_
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -2561,10 +2612,10 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
// optional int32 start = 1;
case 1: {
if (tag == 8) {
+ set_has_start();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &start_)));
- set_has_start();
} else {
goto handle_unusual;
}
@@ -2576,10 +2627,10 @@ bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_end:
+ set_has_end();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
- set_has_end();
} else {
goto handle_unusual;
}
@@ -2631,6 +2682,7 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
::google::protobuf::uint8* DescriptorProto_ExtensionRange::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto.ExtensionRange)
// optional int32 start = 1;
if (has_start()) {
@@ -2650,9 +2702,9 @@ void DescriptorProto_ExtensionRange::SerializeWithCachedSizes(
return target;
}
-int DescriptorProto_ExtensionRange::ByteSize() const {
+size_t DescriptorProto_ExtensionRange::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.DescriptorProto.ExtensionRange)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 3u) {
// optional int32 start = 1;
@@ -2675,18 +2727,17 @@ int DescriptorProto_ExtensionRange::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DescriptorProto_ExtensionRange::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const DescriptorProto_ExtensionRange* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const DescriptorProto_ExtensionRange* source =
::google::protobuf::internal::DynamicCastToGenerated<const DescriptorProto_ExtensionRange>(
&from);
if (source == NULL) {
@@ -2694,15 +2745,21 @@ void DescriptorProto_ExtensionRange::MergeFrom(const ::google::protobuf::Message
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DescriptorProto.ExtensionRange)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ExtensionRange)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void DescriptorProto_ExtensionRange::UnsafeMergeFrom(const DescriptorProto_ExtensionRange& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_start()) {
set_start(from.start());
@@ -2712,7 +2769,8 @@ void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRa
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -2727,7 +2785,7 @@ void DescriptorProto_ExtensionRange::CopyFrom(const DescriptorProto_ExtensionRan
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.DescriptorProto.ExtensionRange)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool DescriptorProto_ExtensionRange::IsInitialized() const {
@@ -2765,6 +2823,7 @@ const int DescriptorProto_ReservedRange::kEndFieldNumber;
DescriptorProto_ReservedRange::DescriptorProto_ReservedRange()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto.ReservedRange)
}
@@ -2776,15 +2835,14 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorPro
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ReservedRange)
}
void DescriptorProto_ReservedRange::SharedCtor() {
_cached_size_ = 0;
- start_ = 0;
- end_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&start_, 0, reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&start_) + sizeof(end_));
}
DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() {
@@ -2793,8 +2851,6 @@ DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() {
}
void DescriptorProto_ReservedRange::SharedDtor() {
- if (this != default_instance_) {
- }
}
void DescriptorProto_ReservedRange::SetCachedSize(int size) const {
@@ -2808,11 +2864,11 @@ const ::google::protobuf::Descriptor* DescriptorProto_ReservedRange::descriptor(
}
const DescriptorProto_ReservedRange& DescriptorProto_ReservedRange::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-DescriptorProto_ReservedRange* DescriptorProto_ReservedRange::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ReservedRange> DescriptorProto_ReservedRange_default_instance_;
DescriptorProto_ReservedRange* DescriptorProto_ReservedRange::New(::google::protobuf::Arena* arena) const {
DescriptorProto_ReservedRange* n = new DescriptorProto_ReservedRange;
@@ -2836,7 +2892,7 @@ void DescriptorProto_ReservedRange::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -2845,7 +2901,7 @@ void DescriptorProto_ReservedRange::Clear() {
#undef ZR_HELPER_
#undef ZR_
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -2864,10 +2920,10 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
// optional int32 start = 1;
case 1: {
if (tag == 8) {
+ set_has_start();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &start_)));
- set_has_start();
} else {
goto handle_unusual;
}
@@ -2879,10 +2935,10 @@ bool DescriptorProto_ReservedRange::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_end:
+ set_has_end();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
- set_has_end();
} else {
goto handle_unusual;
}
@@ -2934,6 +2990,7 @@ void DescriptorProto_ReservedRange::SerializeWithCachedSizes(
::google::protobuf::uint8* DescriptorProto_ReservedRange::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto.ReservedRange)
// optional int32 start = 1;
if (has_start()) {
@@ -2953,9 +3010,9 @@ void DescriptorProto_ReservedRange::SerializeWithCachedSizes(
return target;
}
-int DescriptorProto_ReservedRange::ByteSize() const {
+size_t DescriptorProto_ReservedRange::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.DescriptorProto.ReservedRange)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 3u) {
// optional int32 start = 1;
@@ -2978,18 +3035,17 @@ int DescriptorProto_ReservedRange::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DescriptorProto_ReservedRange::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto.ReservedRange)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const DescriptorProto_ReservedRange* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const DescriptorProto_ReservedRange* source =
::google::protobuf::internal::DynamicCastToGenerated<const DescriptorProto_ReservedRange>(
&from);
if (source == NULL) {
@@ -2997,15 +3053,21 @@ void DescriptorProto_ReservedRange::MergeFrom(const ::google::protobuf::Message&
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DescriptorProto.ReservedRange)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRange& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto.ReservedRange)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void DescriptorProto_ReservedRange::UnsafeMergeFrom(const DescriptorProto_ReservedRange& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_start()) {
set_start(from.start());
@@ -3015,7 +3077,8 @@ void DescriptorProto_ReservedRange::MergeFrom(const DescriptorProto_ReservedRang
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -3030,7 +3093,7 @@ void DescriptorProto_ReservedRange::CopyFrom(const DescriptorProto_ReservedRange
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.DescriptorProto.ReservedRange)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool DescriptorProto_ReservedRange::IsInitialized() const {
@@ -3076,28 +3139,28 @@ const int DescriptorProto::kReservedNameFieldNumber;
DescriptorProto::DescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DescriptorProto)
}
void DescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::MessageOptions*>(&::google::protobuf::MessageOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::MessageOptions*>(
+ ::google::protobuf::MessageOptions::internal_default_instance());
}
DescriptorProto::DescriptorProto(const DescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto)
}
void DescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
DescriptorProto::~DescriptorProto() {
@@ -3107,7 +3170,7 @@ DescriptorProto::~DescriptorProto() {
void DescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &DescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -3123,11 +3186,11 @@ const ::google::protobuf::Descriptor* DescriptorProto::descriptor() {
}
const DescriptorProto& DescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-DescriptorProto* DescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto> DescriptorProto_default_instance_;
DescriptorProto* DescriptorProto::New(::google::protobuf::Arena* arena) const {
DescriptorProto* n = new DescriptorProto;
@@ -3155,7 +3218,7 @@ void DescriptorProto::Clear() {
oneof_decl_.Clear();
reserved_range_.Clear();
reserved_name_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -3435,6 +3498,7 @@ void DescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* DescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -3521,9 +3585,9 @@ void DescriptorProto::SerializeWithCachedSizes(
return target;
}
-int DescriptorProto::ByteSize() const {
+size_t DescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.DescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 129u) {
// optional string name = 1;
@@ -3542,63 +3606,85 @@ int DescriptorProto::ByteSize() const {
}
// repeated .google.protobuf.FieldDescriptorProto field = 2;
- total_size += 1 * this->field_size();
- for (int i = 0; i < this->field_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->field(i));
+ {
+ unsigned int count = this->field_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->field(i));
+ }
}
// repeated .google.protobuf.FieldDescriptorProto extension = 6;
- total_size += 1 * this->extension_size();
- for (int i = 0; i < this->extension_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->extension(i));
+ {
+ unsigned int count = this->extension_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->extension(i));
+ }
}
// repeated .google.protobuf.DescriptorProto nested_type = 3;
- total_size += 1 * this->nested_type_size();
- for (int i = 0; i < this->nested_type_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->nested_type(i));
+ {
+ unsigned int count = this->nested_type_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->nested_type(i));
+ }
}
// repeated .google.protobuf.EnumDescriptorProto enum_type = 4;
- total_size += 1 * this->enum_type_size();
- for (int i = 0; i < this->enum_type_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->enum_type(i));
+ {
+ unsigned int count = this->enum_type_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->enum_type(i));
+ }
}
// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
- total_size += 1 * this->extension_range_size();
- for (int i = 0; i < this->extension_range_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->extension_range(i));
+ {
+ unsigned int count = this->extension_range_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->extension_range(i));
+ }
}
// repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;
- total_size += 1 * this->oneof_decl_size();
- for (int i = 0; i < this->oneof_decl_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->oneof_decl(i));
+ {
+ unsigned int count = this->oneof_decl_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->oneof_decl(i));
+ }
}
// repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
- total_size += 1 * this->reserved_range_size();
- for (int i = 0; i < this->reserved_range_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->reserved_range(i));
+ {
+ unsigned int count = this->reserved_range_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->reserved_range(i));
+ }
}
// repeated string reserved_name = 10;
- total_size += 1 * this->reserved_name_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->reserved_name_size());
for (int i = 0; i < this->reserved_name_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->reserved_name(i));
@@ -3609,18 +3695,17 @@ int DescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const DescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const DescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const DescriptorProto>(
&from);
if (source == NULL) {
@@ -3628,15 +3713,21 @@ void DescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void DescriptorProto::MergeFrom(const DescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void DescriptorProto::UnsafeMergeFrom(const DescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
field_.MergeFrom(from.field_);
extension_.MergeFrom(from.extension_);
nested_type_.MergeFrom(from.nested_type_);
@@ -3644,7 +3735,7 @@ void DescriptorProto::MergeFrom(const DescriptorProto& from) {
extension_range_.MergeFrom(from.extension_range_);
oneof_decl_.MergeFrom(from.oneof_decl_);
reserved_range_.MergeFrom(from.reserved_range_);
- reserved_name_.MergeFrom(from.reserved_name_);
+ reserved_name_.UnsafeMergeFrom(from.reserved_name_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_has_name();
@@ -3655,7 +3746,8 @@ void DescriptorProto::MergeFrom(const DescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -3670,7 +3762,7 @@ void DescriptorProto::CopyFrom(const DescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.DescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool DescriptorProto::IsInitialized() const {
@@ -3731,11 +3823,11 @@ void DescriptorProto_ExtensionRange::clear_start() {
start_ = 0;
clear_has_start();
}
- ::google::protobuf::int32 DescriptorProto_ExtensionRange::start() const {
+::google::protobuf::int32 DescriptorProto_ExtensionRange::start() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.start)
return start_;
}
- void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 value) {
+void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 value) {
set_has_start();
start_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.start)
@@ -3755,16 +3847,19 @@ void DescriptorProto_ExtensionRange::clear_end() {
end_ = 0;
clear_has_end();
}
- ::google::protobuf::int32 DescriptorProto_ExtensionRange::end() const {
+::google::protobuf::int32 DescriptorProto_ExtensionRange::end() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.end)
return end_;
}
- void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 value) {
+void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 value) {
set_has_end();
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.end)
}
+inline const DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::internal_default_instance() {
+ return &DescriptorProto_ExtensionRange_default_instance_.get();
+}
// -------------------------------------------------------------------
// DescriptorProto_ReservedRange
@@ -3783,11 +3878,11 @@ void DescriptorProto_ReservedRange::clear_start() {
start_ = 0;
clear_has_start();
}
- ::google::protobuf::int32 DescriptorProto_ReservedRange::start() const {
+::google::protobuf::int32 DescriptorProto_ReservedRange::start() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.start)
return start_;
}
- void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 value) {
+void DescriptorProto_ReservedRange::set_start(::google::protobuf::int32 value) {
set_has_start();
start_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.start)
@@ -3807,16 +3902,19 @@ void DescriptorProto_ReservedRange::clear_end() {
end_ = 0;
clear_has_end();
}
- ::google::protobuf::int32 DescriptorProto_ReservedRange::end() const {
+::google::protobuf::int32 DescriptorProto_ReservedRange::end() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.end)
return end_;
}
- void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 value) {
+void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 value) {
set_has_end();
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.end)
}
+inline const DescriptorProto_ReservedRange* DescriptorProto_ReservedRange::internal_default_instance() {
+ return &DescriptorProto_ReservedRange_default_instance_.get();
+}
// -------------------------------------------------------------------
// DescriptorProto
@@ -3835,37 +3933,37 @@ void DescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& DescriptorProto::name() const {
+const ::std::string& DescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void DescriptorProto::set_name(const ::std::string& value) {
+void DescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.name)
}
- void DescriptorProto::set_name(const char* value) {
+void DescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.name)
}
- void DescriptorProto::set_name(const char* value, size_t size) {
+void DescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.name)
}
- ::std::string* DescriptorProto::mutable_name() {
+::std::string* DescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* DescriptorProto::release_name() {
+::std::string* DescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void DescriptorProto::set_allocated_name(::std::string* name) {
+void DescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -4071,7 +4169,8 @@ void DescriptorProto::clear_options() {
}
const ::google::protobuf::MessageOptions& DescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::MessageOptions::internal_default_instance();
}
::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
set_has_options();
@@ -4136,54 +4235,57 @@ int DescriptorProto::reserved_name_size() const {
void DescriptorProto::clear_reserved_name() {
reserved_name_.Clear();
}
- const ::std::string& DescriptorProto::reserved_name(int index) const {
+const ::std::string& DescriptorProto::reserved_name(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_name)
return reserved_name_.Get(index);
}
- ::std::string* DescriptorProto::mutable_reserved_name(int index) {
+::std::string* DescriptorProto::mutable_reserved_name(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_name)
return reserved_name_.Mutable(index);
}
- void DescriptorProto::set_reserved_name(int index, const ::std::string& value) {
+void DescriptorProto::set_reserved_name(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name)
reserved_name_.Mutable(index)->assign(value);
}
- void DescriptorProto::set_reserved_name(int index, const char* value) {
+void DescriptorProto::set_reserved_name(int index, const char* value) {
reserved_name_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.reserved_name)
}
- void DescriptorProto::set_reserved_name(int index, const char* value, size_t size) {
+void DescriptorProto::set_reserved_name(int index, const char* value, size_t size) {
reserved_name_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.reserved_name)
}
- ::std::string* DescriptorProto::add_reserved_name() {
+::std::string* DescriptorProto::add_reserved_name() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.DescriptorProto.reserved_name)
return reserved_name_.Add();
}
- void DescriptorProto::add_reserved_name(const ::std::string& value) {
+void DescriptorProto::add_reserved_name(const ::std::string& value) {
reserved_name_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name)
}
- void DescriptorProto::add_reserved_name(const char* value) {
+void DescriptorProto::add_reserved_name(const char* value) {
reserved_name_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.DescriptorProto.reserved_name)
}
- void DescriptorProto::add_reserved_name(const char* value, size_t size) {
+void DescriptorProto::add_reserved_name(const char* value, size_t size) {
reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.DescriptorProto.reserved_name)
}
- const ::google::protobuf::RepeatedPtrField< ::std::string>&
+const ::google::protobuf::RepeatedPtrField< ::std::string>&
DescriptorProto::reserved_name() const {
// @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_name)
return reserved_name_;
}
- ::google::protobuf::RepeatedPtrField< ::std::string>*
+::google::protobuf::RepeatedPtrField< ::std::string>*
DescriptorProto::mutable_reserved_name() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_name)
return &reserved_name_;
}
+inline const DescriptorProto* DescriptorProto::internal_default_instance() {
+ return &DescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -4193,7 +4295,7 @@ const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor()
return FieldDescriptorProto_Type_descriptor_;
}
bool FieldDescriptorProto_Type_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 1:
case 2:
case 3:
@@ -4246,7 +4348,7 @@ const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor(
return FieldDescriptorProto_Label_descriptor_;
}
bool FieldDescriptorProto_Label_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 1:
case 2:
case 3:
@@ -4279,36 +4381,36 @@ const int FieldDescriptorProto::kOptionsFieldNumber;
FieldDescriptorProto::FieldDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldDescriptorProto)
}
void FieldDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::FieldOptions*>(&::google::protobuf::FieldOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::FieldOptions*>(
+ ::google::protobuf::FieldOptions::internal_default_instance());
}
FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldDescriptorProto)
}
void FieldDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- number_ = 0;
- label_ = 1;
- type_ = 1;
type_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
extendee_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- oneof_index_ = 0;
json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&number_, 0, reinterpret_cast<char*>(&oneof_index_) -
+ reinterpret_cast<char*>(&number_) + sizeof(oneof_index_));
+ label_ = 1;
+ type_ = 1;
}
FieldDescriptorProto::~FieldDescriptorProto() {
@@ -4322,7 +4424,7 @@ void FieldDescriptorProto::SharedDtor() {
extendee_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
default_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
json_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &FieldDescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -4338,11 +4440,11 @@ const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() {
}
const FieldDescriptorProto& FieldDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-FieldDescriptorProto* FieldDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FieldDescriptorProto> FieldDescriptorProto_default_instance_;
FieldDescriptorProto* FieldDescriptorProto::New(::google::protobuf::Arena* arena) const {
FieldDescriptorProto* n = new FieldDescriptorProto;
@@ -4354,11 +4456,27 @@ FieldDescriptorProto* FieldDescriptorProto::New(::google::protobuf::Arena* arena
void FieldDescriptorProto::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.FieldDescriptorProto)
+#if defined(__clang__)
+#define ZR_HELPER_(f) \
+ _Pragma("clang diagnostic push") \
+ _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
+ __builtin_offsetof(FieldDescriptorProto, f) \
+ _Pragma("clang diagnostic pop")
+#else
+#define ZR_HELPER_(f) reinterpret_cast<char*>(\
+ &reinterpret_cast<FieldDescriptorProto*>(16)->f)
+#endif
+
+#define ZR_(first, last) do {\
+ ::memset(&(first), 0,\
+ ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
+} while (0)
+
if (_has_bits_[0 / 32] & 255u) {
+ ZR_(number_, oneof_index_);
if (has_name()) {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- number_ = 0;
label_ = 1;
type_ = 1;
if (has_type_name()) {
@@ -4370,7 +4488,6 @@ void FieldDescriptorProto::Clear() {
if (has_default_value()) {
default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- oneof_index_ = 0;
}
if (_has_bits_[8 / 32] & 768u) {
if (has_json_name()) {
@@ -4380,7 +4497,11 @@ void FieldDescriptorProto::Clear() {
if (options_ != NULL) options_->::google::protobuf::FieldOptions::Clear();
}
}
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+
+#undef ZR_HELPER_
+#undef ZR_
+
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -4433,10 +4554,10 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_number:
+ set_has_number();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &number_)));
- set_has_number();
} else {
goto handle_unusual;
}
@@ -4535,10 +4656,10 @@ bool FieldDescriptorProto::MergePartialFromCodedStream(
case 9: {
if (tag == 72) {
parse_oneof_index:
+ set_has_oneof_index();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &oneof_index_)));
- set_has_oneof_index();
} else {
goto handle_unusual;
}
@@ -4675,6 +4796,7 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* FieldDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -4768,9 +4890,9 @@ void FieldDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int FieldDescriptorProto::ByteSize() const {
+size_t FieldDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FieldDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 255u) {
// optional string name = 1;
@@ -4849,18 +4971,17 @@ int FieldDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FieldDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FieldDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FieldDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const FieldDescriptorProto>(
&from);
if (source == NULL) {
@@ -4868,15 +4989,21 @@ void FieldDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FieldDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void FieldDescriptorProto::UnsafeMergeFrom(const FieldDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_has_name();
@@ -4917,7 +5044,8 @@ void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -4932,7 +5060,7 @@ void FieldDescriptorProto::CopyFrom(const FieldDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FieldDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FieldDescriptorProto::IsInitialized() const {
@@ -4988,37 +5116,37 @@ void FieldDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& FieldDescriptorProto::name() const {
+const ::std::string& FieldDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_name(const ::std::string& value) {
+void FieldDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.name)
}
- void FieldDescriptorProto::set_name(const char* value) {
+void FieldDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.name)
}
- void FieldDescriptorProto::set_name(const char* value, size_t size) {
+void FieldDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.name)
}
- ::std::string* FieldDescriptorProto::mutable_name() {
+::std::string* FieldDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FieldDescriptorProto::release_name() {
+::std::string* FieldDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_allocated_name(::std::string* name) {
+void FieldDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -5042,11 +5170,11 @@ void FieldDescriptorProto::clear_number() {
number_ = 0;
clear_has_number();
}
- ::google::protobuf::int32 FieldDescriptorProto::number() const {
+::google::protobuf::int32 FieldDescriptorProto::number() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.number)
return number_;
}
- void FieldDescriptorProto::set_number(::google::protobuf::int32 value) {
+void FieldDescriptorProto::set_number(::google::protobuf::int32 value) {
set_has_number();
number_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.number)
@@ -5066,11 +5194,11 @@ void FieldDescriptorProto::clear_label() {
label_ = 1;
clear_has_label();
}
- ::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::label() const {
+::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::label() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.label)
return static_cast< ::google::protobuf::FieldDescriptorProto_Label >(label_);
}
- void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorProto_Label value) {
+void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorProto_Label value) {
assert(::google::protobuf::FieldDescriptorProto_Label_IsValid(value));
set_has_label();
label_ = value;
@@ -5091,11 +5219,11 @@ void FieldDescriptorProto::clear_type() {
type_ = 1;
clear_has_type();
}
- ::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type() const {
+::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type)
return static_cast< ::google::protobuf::FieldDescriptorProto_Type >(type_);
}
- void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorProto_Type value) {
+void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorProto_Type value) {
assert(::google::protobuf::FieldDescriptorProto_Type_IsValid(value));
set_has_type();
type_ = value;
@@ -5116,37 +5244,37 @@ void FieldDescriptorProto::clear_type_name() {
type_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_type_name();
}
- const ::std::string& FieldDescriptorProto::type_name() const {
+const ::std::string& FieldDescriptorProto::type_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type_name)
return type_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_type_name(const ::std::string& value) {
+void FieldDescriptorProto::set_type_name(const ::std::string& value) {
set_has_type_name();
type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type_name)
}
- void FieldDescriptorProto::set_type_name(const char* value) {
+void FieldDescriptorProto::set_type_name(const char* value) {
set_has_type_name();
type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.type_name)
}
- void FieldDescriptorProto::set_type_name(const char* value, size_t size) {
+void FieldDescriptorProto::set_type_name(const char* value, size_t size) {
set_has_type_name();
type_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.type_name)
}
- ::std::string* FieldDescriptorProto::mutable_type_name() {
+::std::string* FieldDescriptorProto::mutable_type_name() {
set_has_type_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.type_name)
return type_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FieldDescriptorProto::release_type_name() {
+::std::string* FieldDescriptorProto::release_type_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name)
clear_has_type_name();
return type_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) {
+void FieldDescriptorProto::set_allocated_type_name(::std::string* type_name) {
if (type_name != NULL) {
set_has_type_name();
} else {
@@ -5170,37 +5298,37 @@ void FieldDescriptorProto::clear_extendee() {
extendee_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_extendee();
}
- const ::std::string& FieldDescriptorProto::extendee() const {
+const ::std::string& FieldDescriptorProto::extendee() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.extendee)
return extendee_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_extendee(const ::std::string& value) {
+void FieldDescriptorProto::set_extendee(const ::std::string& value) {
set_has_extendee();
extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.extendee)
}
- void FieldDescriptorProto::set_extendee(const char* value) {
+void FieldDescriptorProto::set_extendee(const char* value) {
set_has_extendee();
extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.extendee)
}
- void FieldDescriptorProto::set_extendee(const char* value, size_t size) {
+void FieldDescriptorProto::set_extendee(const char* value, size_t size) {
set_has_extendee();
extendee_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.extendee)
}
- ::std::string* FieldDescriptorProto::mutable_extendee() {
+::std::string* FieldDescriptorProto::mutable_extendee() {
set_has_extendee();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.extendee)
return extendee_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FieldDescriptorProto::release_extendee() {
+::std::string* FieldDescriptorProto::release_extendee() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee)
clear_has_extendee();
return extendee_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) {
+void FieldDescriptorProto::set_allocated_extendee(::std::string* extendee) {
if (extendee != NULL) {
set_has_extendee();
} else {
@@ -5224,37 +5352,37 @@ void FieldDescriptorProto::clear_default_value() {
default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_default_value();
}
- const ::std::string& FieldDescriptorProto::default_value() const {
+const ::std::string& FieldDescriptorProto::default_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.default_value)
return default_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_default_value(const ::std::string& value) {
+void FieldDescriptorProto::set_default_value(const ::std::string& value) {
set_has_default_value();
default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.default_value)
}
- void FieldDescriptorProto::set_default_value(const char* value) {
+void FieldDescriptorProto::set_default_value(const char* value) {
set_has_default_value();
default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.default_value)
}
- void FieldDescriptorProto::set_default_value(const char* value, size_t size) {
+void FieldDescriptorProto::set_default_value(const char* value, size_t size) {
set_has_default_value();
default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.default_value)
}
- ::std::string* FieldDescriptorProto::mutable_default_value() {
+::std::string* FieldDescriptorProto::mutable_default_value() {
set_has_default_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.default_value)
return default_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FieldDescriptorProto::release_default_value() {
+::std::string* FieldDescriptorProto::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value)
clear_has_default_value();
return default_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) {
+void FieldDescriptorProto::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
set_has_default_value();
} else {
@@ -5278,11 +5406,11 @@ void FieldDescriptorProto::clear_oneof_index() {
oneof_index_ = 0;
clear_has_oneof_index();
}
- ::google::protobuf::int32 FieldDescriptorProto::oneof_index() const {
+::google::protobuf::int32 FieldDescriptorProto::oneof_index() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.oneof_index)
return oneof_index_;
}
- void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 value) {
+void FieldDescriptorProto::set_oneof_index(::google::protobuf::int32 value) {
set_has_oneof_index();
oneof_index_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.oneof_index)
@@ -5302,37 +5430,37 @@ void FieldDescriptorProto::clear_json_name() {
json_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_json_name();
}
- const ::std::string& FieldDescriptorProto::json_name() const {
+const ::std::string& FieldDescriptorProto::json_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.json_name)
return json_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_json_name(const ::std::string& value) {
+void FieldDescriptorProto::set_json_name(const ::std::string& value) {
set_has_json_name();
json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.json_name)
}
- void FieldDescriptorProto::set_json_name(const char* value) {
+void FieldDescriptorProto::set_json_name(const char* value) {
set_has_json_name();
json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldDescriptorProto.json_name)
}
- void FieldDescriptorProto::set_json_name(const char* value, size_t size) {
+void FieldDescriptorProto::set_json_name(const char* value, size_t size) {
set_has_json_name();
json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldDescriptorProto.json_name)
}
- ::std::string* FieldDescriptorProto::mutable_json_name() {
+::std::string* FieldDescriptorProto::mutable_json_name() {
set_has_json_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldDescriptorProto.json_name)
return json_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FieldDescriptorProto::release_json_name() {
+::std::string* FieldDescriptorProto::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name)
clear_has_json_name();
return json_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) {
+void FieldDescriptorProto::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
set_has_json_name();
} else {
@@ -5358,7 +5486,8 @@ void FieldDescriptorProto::clear_options() {
}
const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::FieldOptions::internal_default_instance();
}
::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
set_has_options();
@@ -5386,6 +5515,9 @@ void FieldDescriptorProto::set_allocated_options(::google::protobuf::FieldOption
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options)
}
+inline const FieldDescriptorProto* FieldDescriptorProto::internal_default_instance() {
+ return &FieldDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -5397,28 +5529,28 @@ const int OneofDescriptorProto::kOptionsFieldNumber;
OneofDescriptorProto::OneofDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofDescriptorProto)
}
void OneofDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::OneofOptions*>(&::google::protobuf::OneofOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::OneofOptions*>(
+ ::google::protobuf::OneofOptions::internal_default_instance());
}
OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.OneofDescriptorProto)
}
void OneofDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
OneofDescriptorProto::~OneofDescriptorProto() {
@@ -5428,7 +5560,7 @@ OneofDescriptorProto::~OneofDescriptorProto() {
void OneofDescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &OneofDescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -5444,11 +5576,11 @@ const ::google::protobuf::Descriptor* OneofDescriptorProto::descriptor() {
}
const OneofDescriptorProto& OneofDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-OneofDescriptorProto* OneofDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<OneofDescriptorProto> OneofDescriptorProto_default_instance_;
OneofDescriptorProto* OneofDescriptorProto::New(::google::protobuf::Arena* arena) const {
OneofDescriptorProto* n = new OneofDescriptorProto;
@@ -5468,7 +5600,7 @@ void OneofDescriptorProto::Clear() {
if (options_ != NULL) options_->::google::protobuf::OneofOptions::Clear();
}
}
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -5563,6 +5695,7 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* OneofDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.OneofDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -5590,9 +5723,9 @@ void OneofDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int OneofDescriptorProto::ByteSize() const {
+size_t OneofDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.OneofDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 3u) {
// optional string name = 1;
@@ -5615,18 +5748,17 @@ int OneofDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void OneofDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.OneofDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const OneofDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const OneofDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const OneofDescriptorProto>(
&from);
if (source == NULL) {
@@ -5634,15 +5766,21 @@ void OneofDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.OneofDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void OneofDescriptorProto::MergeFrom(const OneofDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.OneofDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void OneofDescriptorProto::UnsafeMergeFrom(const OneofDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_has_name();
@@ -5653,7 +5791,8 @@ void OneofDescriptorProto::MergeFrom(const OneofDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -5668,7 +5807,7 @@ void OneofDescriptorProto::CopyFrom(const OneofDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.OneofDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool OneofDescriptorProto::IsInitialized() const {
@@ -5716,37 +5855,37 @@ void OneofDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& OneofDescriptorProto::name() const {
+const ::std::string& OneofDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void OneofDescriptorProto::set_name(const ::std::string& value) {
+void OneofDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.OneofDescriptorProto.name)
}
- void OneofDescriptorProto::set_name(const char* value) {
+void OneofDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.OneofDescriptorProto.name)
}
- void OneofDescriptorProto::set_name(const char* value, size_t size) {
+void OneofDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.OneofDescriptorProto.name)
}
- ::std::string* OneofDescriptorProto::mutable_name() {
+::std::string* OneofDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.OneofDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* OneofDescriptorProto::release_name() {
+::std::string* OneofDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void OneofDescriptorProto::set_allocated_name(::std::string* name) {
+void OneofDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -5772,7 +5911,8 @@ void OneofDescriptorProto::clear_options() {
}
const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::OneofOptions::internal_default_instance();
}
::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
set_has_options();
@@ -5800,6 +5940,9 @@ void OneofDescriptorProto::set_allocated_options(::google::protobuf::OneofOption
// @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options)
}
+inline const OneofDescriptorProto* OneofDescriptorProto::internal_default_instance() {
+ return &OneofDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -5812,28 +5955,28 @@ const int EnumDescriptorProto::kOptionsFieldNumber;
EnumDescriptorProto::EnumDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumDescriptorProto)
}
void EnumDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::EnumOptions*>(&::google::protobuf::EnumOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::EnumOptions*>(
+ ::google::protobuf::EnumOptions::internal_default_instance());
}
EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto)
}
void EnumDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
EnumDescriptorProto::~EnumDescriptorProto() {
@@ -5843,7 +5986,7 @@ EnumDescriptorProto::~EnumDescriptorProto() {
void EnumDescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &EnumDescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -5859,11 +6002,11 @@ const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() {
}
const EnumDescriptorProto& EnumDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-EnumDescriptorProto* EnumDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto> EnumDescriptorProto_default_instance_;
EnumDescriptorProto* EnumDescriptorProto::New(::google::protobuf::Arena* arena) const {
EnumDescriptorProto* n = new EnumDescriptorProto;
@@ -5884,7 +6027,7 @@ void EnumDescriptorProto::Clear() {
}
}
value_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -6002,6 +6145,7 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* EnumDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -6036,9 +6180,9 @@ void EnumDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int EnumDescriptorProto::ByteSize() const {
+size_t EnumDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 5u) {
// optional string name = 1;
@@ -6057,11 +6201,14 @@ int EnumDescriptorProto::ByteSize() const {
}
// repeated .google.protobuf.EnumValueDescriptorProto value = 2;
- total_size += 1 * this->value_size();
- for (int i = 0; i < this->value_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->value(i));
+ {
+ unsigned int count = this->value_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->value(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -6069,18 +6216,17 @@ int EnumDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void EnumDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const EnumDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const EnumDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const EnumDescriptorProto>(
&from);
if (source == NULL) {
@@ -6088,15 +6234,21 @@ void EnumDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void EnumDescriptorProto::UnsafeMergeFrom(const EnumDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
value_.MergeFrom(from.value_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
@@ -6108,7 +6260,8 @@ void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -6123,7 +6276,7 @@ void EnumDescriptorProto::CopyFrom(const EnumDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.EnumDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool EnumDescriptorProto::IsInitialized() const {
@@ -6173,37 +6326,37 @@ void EnumDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& EnumDescriptorProto::name() const {
+const ::std::string& EnumDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void EnumDescriptorProto::set_name(const ::std::string& value) {
+void EnumDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.name)
}
- void EnumDescriptorProto::set_name(const char* value) {
+void EnumDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.name)
}
- void EnumDescriptorProto::set_name(const char* value, size_t size) {
+void EnumDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.name)
}
- ::std::string* EnumDescriptorProto::mutable_name() {
+::std::string* EnumDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* EnumDescriptorProto::release_name() {
+::std::string* EnumDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void EnumDescriptorProto::set_allocated_name(::std::string* name) {
+void EnumDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -6259,7 +6412,8 @@ void EnumDescriptorProto::clear_options() {
}
const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::EnumOptions::internal_default_instance();
}
::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
set_has_options();
@@ -6287,6 +6441,9 @@ void EnumDescriptorProto::set_allocated_options(::google::protobuf::EnumOptions*
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options)
}
+inline const EnumDescriptorProto* EnumDescriptorProto::internal_default_instance() {
+ return &EnumDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -6299,29 +6456,29 @@ const int EnumValueDescriptorProto::kOptionsFieldNumber;
EnumValueDescriptorProto::EnumValueDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueDescriptorProto)
}
void EnumValueDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::EnumValueOptions*>(&::google::protobuf::EnumValueOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::EnumValueOptions*>(
+ ::google::protobuf::EnumValueOptions::internal_default_instance());
}
EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueDescriptorProto)
}
void EnumValueDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- number_ = 0;
options_ = NULL;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ number_ = 0;
}
EnumValueDescriptorProto::~EnumValueDescriptorProto() {
@@ -6331,7 +6488,7 @@ EnumValueDescriptorProto::~EnumValueDescriptorProto() {
void EnumValueDescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &EnumValueDescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -6347,11 +6504,11 @@ const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() {
}
const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-EnumValueDescriptorProto* EnumValueDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<EnumValueDescriptorProto> EnumValueDescriptorProto_default_instance_;
EnumValueDescriptorProto* EnumValueDescriptorProto::New(::google::protobuf::Arena* arena) const {
EnumValueDescriptorProto* n = new EnumValueDescriptorProto;
@@ -6372,7 +6529,7 @@ void EnumValueDescriptorProto::Clear() {
if (options_ != NULL) options_->::google::protobuf::EnumValueOptions::Clear();
}
}
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -6408,10 +6565,10 @@ bool EnumValueDescriptorProto::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_number:
+ set_has_number();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &number_)));
- set_has_number();
} else {
goto handle_unusual;
}
@@ -6487,6 +6644,7 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* EnumValueDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValueDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -6519,9 +6677,9 @@ void EnumValueDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int EnumValueDescriptorProto::ByteSize() const {
+size_t EnumValueDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumValueDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 7u) {
// optional string name = 1;
@@ -6551,18 +6709,17 @@ int EnumValueDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void EnumValueDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValueDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const EnumValueDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const EnumValueDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const EnumValueDescriptorProto>(
&from);
if (source == NULL) {
@@ -6570,15 +6727,21 @@ void EnumValueDescriptorProto::MergeFrom(const ::google::protobuf::Message& from
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumValueDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValueDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void EnumValueDescriptorProto::UnsafeMergeFrom(const EnumValueDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_has_name();
@@ -6592,7 +6755,8 @@ void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -6607,7 +6771,7 @@ void EnumValueDescriptorProto::CopyFrom(const EnumValueDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.EnumValueDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool EnumValueDescriptorProto::IsInitialized() const {
@@ -6656,37 +6820,37 @@ void EnumValueDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& EnumValueDescriptorProto::name() const {
+const ::std::string& EnumValueDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void EnumValueDescriptorProto::set_name(const ::std::string& value) {
+void EnumValueDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.name)
}
- void EnumValueDescriptorProto::set_name(const char* value) {
+void EnumValueDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumValueDescriptorProto.name)
}
- void EnumValueDescriptorProto::set_name(const char* value, size_t size) {
+void EnumValueDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValueDescriptorProto.name)
}
- ::std::string* EnumValueDescriptorProto::mutable_name() {
+::std::string* EnumValueDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* EnumValueDescriptorProto::release_name() {
+::std::string* EnumValueDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
+void EnumValueDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -6710,11 +6874,11 @@ void EnumValueDescriptorProto::clear_number() {
number_ = 0;
clear_has_number();
}
- ::google::protobuf::int32 EnumValueDescriptorProto::number() const {
+::google::protobuf::int32 EnumValueDescriptorProto::number() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.number)
return number_;
}
- void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value) {
+void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value) {
set_has_number();
number_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.number)
@@ -6736,7 +6900,8 @@ void EnumValueDescriptorProto::clear_options() {
}
const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::EnumValueOptions::internal_default_instance();
}
::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
set_has_options();
@@ -6764,6 +6929,9 @@ void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::EnumVal
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
}
+inline const EnumValueDescriptorProto* EnumValueDescriptorProto::internal_default_instance() {
+ return &EnumValueDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -6776,28 +6944,28 @@ const int ServiceDescriptorProto::kOptionsFieldNumber;
ServiceDescriptorProto::ServiceDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceDescriptorProto)
}
void ServiceDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::ServiceOptions*>(&::google::protobuf::ServiceOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::ServiceOptions*>(
+ ::google::protobuf::ServiceOptions::internal_default_instance());
}
ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceDescriptorProto)
}
void ServiceDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
ServiceDescriptorProto::~ServiceDescriptorProto() {
@@ -6807,7 +6975,7 @@ ServiceDescriptorProto::~ServiceDescriptorProto() {
void ServiceDescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &ServiceDescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -6823,11 +6991,11 @@ const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() {
}
const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-ServiceDescriptorProto* ServiceDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<ServiceDescriptorProto> ServiceDescriptorProto_default_instance_;
ServiceDescriptorProto* ServiceDescriptorProto::New(::google::protobuf::Arena* arena) const {
ServiceDescriptorProto* n = new ServiceDescriptorProto;
@@ -6848,7 +7016,7 @@ void ServiceDescriptorProto::Clear() {
}
}
method_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -6966,6 +7134,7 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* ServiceDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ServiceDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -7000,9 +7169,9 @@ void ServiceDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int ServiceDescriptorProto::ByteSize() const {
+size_t ServiceDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.ServiceDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 5u) {
// optional string name = 1;
@@ -7021,11 +7190,14 @@ int ServiceDescriptorProto::ByteSize() const {
}
// repeated .google.protobuf.MethodDescriptorProto method = 2;
- total_size += 1 * this->method_size();
- for (int i = 0; i < this->method_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->method(i));
+ {
+ unsigned int count = this->method_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->method(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -7033,18 +7205,17 @@ int ServiceDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void ServiceDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ServiceDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const ServiceDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const ServiceDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const ServiceDescriptorProto>(
&from);
if (source == NULL) {
@@ -7052,15 +7223,21 @@ void ServiceDescriptorProto::MergeFrom(const ::google::protobuf::Message& from)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ServiceDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ServiceDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void ServiceDescriptorProto::UnsafeMergeFrom(const ServiceDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
method_.MergeFrom(from.method_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
@@ -7072,7 +7249,8 @@ void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -7087,7 +7265,7 @@ void ServiceDescriptorProto::CopyFrom(const ServiceDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.ServiceDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool ServiceDescriptorProto::IsInitialized() const {
@@ -7137,37 +7315,37 @@ void ServiceDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& ServiceDescriptorProto::name() const {
+const ::std::string& ServiceDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void ServiceDescriptorProto::set_name(const ::std::string& value) {
+void ServiceDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.ServiceDescriptorProto.name)
}
- void ServiceDescriptorProto::set_name(const char* value) {
+void ServiceDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.ServiceDescriptorProto.name)
}
- void ServiceDescriptorProto::set_name(const char* value, size_t size) {
+void ServiceDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.ServiceDescriptorProto.name)
}
- ::std::string* ServiceDescriptorProto::mutable_name() {
+::std::string* ServiceDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* ServiceDescriptorProto::release_name() {
+::std::string* ServiceDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
+void ServiceDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -7223,7 +7401,8 @@ void ServiceDescriptorProto::clear_options() {
}
const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::ServiceOptions::internal_default_instance();
}
::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
set_has_options();
@@ -7251,6 +7430,9 @@ void ServiceDescriptorProto::set_allocated_options(::google::protobuf::ServiceOp
// @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options)
}
+inline const ServiceDescriptorProto* ServiceDescriptorProto::internal_default_instance() {
+ return &ServiceDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -7266,32 +7448,32 @@ const int MethodDescriptorProto::kServerStreamingFieldNumber;
MethodDescriptorProto::MethodDescriptorProto()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodDescriptorProto)
}
void MethodDescriptorProto::InitAsDefaultInstance() {
- options_ = const_cast< ::google::protobuf::MethodOptions*>(&::google::protobuf::MethodOptions::default_instance());
+ options_ = const_cast< ::google::protobuf::MethodOptions*>(
+ ::google::protobuf::MethodOptions::internal_default_instance());
}
MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.MethodDescriptorProto)
}
void MethodDescriptorProto::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
input_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
output_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
options_ = NULL;
- client_streaming_ = false;
- server_streaming_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&client_streaming_, 0, reinterpret_cast<char*>(&server_streaming_) -
+ reinterpret_cast<char*>(&client_streaming_) + sizeof(server_streaming_));
}
MethodDescriptorProto::~MethodDescriptorProto() {
@@ -7303,7 +7485,7 @@ void MethodDescriptorProto::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
input_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
output_type_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ if (this != &MethodDescriptorProto_default_instance_.get()) {
delete options_;
}
}
@@ -7319,11 +7501,11 @@ const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() {
}
const MethodDescriptorProto& MethodDescriptorProto::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-MethodDescriptorProto* MethodDescriptorProto::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<MethodDescriptorProto> MethodDescriptorProto_default_instance_;
MethodDescriptorProto* MethodDescriptorProto::New(::google::protobuf::Arena* arena) const {
MethodDescriptorProto* n = new MethodDescriptorProto;
@@ -7347,7 +7529,7 @@ void MethodDescriptorProto::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -7370,7 +7552,7 @@ void MethodDescriptorProto::Clear() {
#undef ZR_HELPER_
#undef ZR_
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -7453,10 +7635,10 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
case 5: {
if (tag == 40) {
parse_client_streaming:
+ set_has_client_streaming();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &client_streaming_)));
- set_has_client_streaming();
} else {
goto handle_unusual;
}
@@ -7468,10 +7650,10 @@ bool MethodDescriptorProto::MergePartialFromCodedStream(
case 6: {
if (tag == 48) {
parse_server_streaming:
+ set_has_server_streaming();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &server_streaming_)));
- set_has_server_streaming();
} else {
goto handle_unusual;
}
@@ -7559,6 +7741,7 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
::google::protobuf::uint8* MethodDescriptorProto::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MethodDescriptorProto)
// optional string name = 1;
if (has_name()) {
@@ -7618,9 +7801,9 @@ void MethodDescriptorProto::SerializeWithCachedSizes(
return target;
}
-int MethodDescriptorProto::ByteSize() const {
+size_t MethodDescriptorProto::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.MethodDescriptorProto)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 63u) {
// optional string name = 1;
@@ -7667,18 +7850,17 @@ int MethodDescriptorProto::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MethodDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MethodDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const MethodDescriptorProto* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const MethodDescriptorProto* source =
::google::protobuf::internal::DynamicCastToGenerated<const MethodDescriptorProto>(
&from);
if (source == NULL) {
@@ -7686,15 +7868,21 @@ void MethodDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.MethodDescriptorProto)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MethodDescriptorProto)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void MethodDescriptorProto::UnsafeMergeFrom(const MethodDescriptorProto& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_has_name();
@@ -7719,7 +7907,8 @@ void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -7734,7 +7923,7 @@ void MethodDescriptorProto::CopyFrom(const MethodDescriptorProto& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.MethodDescriptorProto)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool MethodDescriptorProto::IsInitialized() const {
@@ -7786,37 +7975,37 @@ void MethodDescriptorProto::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name();
}
- const ::std::string& MethodDescriptorProto::name() const {
+const ::std::string& MethodDescriptorProto::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.name)
return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void MethodDescriptorProto::set_name(const ::std::string& value) {
+void MethodDescriptorProto::set_name(const ::std::string& value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.name)
}
- void MethodDescriptorProto::set_name(const char* value) {
+void MethodDescriptorProto::set_name(const char* value) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.name)
}
- void MethodDescriptorProto::set_name(const char* value, size_t size) {
+void MethodDescriptorProto::set_name(const char* value, size_t size) {
set_has_name();
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.name)
}
- ::std::string* MethodDescriptorProto::mutable_name() {
+::std::string* MethodDescriptorProto::mutable_name() {
set_has_name();
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* MethodDescriptorProto::release_name() {
+::std::string* MethodDescriptorProto::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name)
clear_has_name();
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void MethodDescriptorProto::set_allocated_name(::std::string* name) {
+void MethodDescriptorProto::set_allocated_name(::std::string* name) {
if (name != NULL) {
set_has_name();
} else {
@@ -7840,37 +8029,37 @@ void MethodDescriptorProto::clear_input_type() {
input_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_input_type();
}
- const ::std::string& MethodDescriptorProto::input_type() const {
+const ::std::string& MethodDescriptorProto::input_type() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.input_type)
return input_type_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void MethodDescriptorProto::set_input_type(const ::std::string& value) {
+void MethodDescriptorProto::set_input_type(const ::std::string& value) {
set_has_input_type();
input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.input_type)
}
- void MethodDescriptorProto::set_input_type(const char* value) {
+void MethodDescriptorProto::set_input_type(const char* value) {
set_has_input_type();
input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.input_type)
}
- void MethodDescriptorProto::set_input_type(const char* value, size_t size) {
+void MethodDescriptorProto::set_input_type(const char* value, size_t size) {
set_has_input_type();
input_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.input_type)
}
- ::std::string* MethodDescriptorProto::mutable_input_type() {
+::std::string* MethodDescriptorProto::mutable_input_type() {
set_has_input_type();
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.input_type)
return input_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* MethodDescriptorProto::release_input_type() {
+::std::string* MethodDescriptorProto::release_input_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type)
clear_has_input_type();
return input_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) {
+void MethodDescriptorProto::set_allocated_input_type(::std::string* input_type) {
if (input_type != NULL) {
set_has_input_type();
} else {
@@ -7894,37 +8083,37 @@ void MethodDescriptorProto::clear_output_type() {
output_type_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_output_type();
}
- const ::std::string& MethodDescriptorProto::output_type() const {
+const ::std::string& MethodDescriptorProto::output_type() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.output_type)
return output_type_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void MethodDescriptorProto::set_output_type(const ::std::string& value) {
+void MethodDescriptorProto::set_output_type(const ::std::string& value) {
set_has_output_type();
output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.output_type)
}
- void MethodDescriptorProto::set_output_type(const char* value) {
+void MethodDescriptorProto::set_output_type(const char* value) {
set_has_output_type();
output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.MethodDescriptorProto.output_type)
}
- void MethodDescriptorProto::set_output_type(const char* value, size_t size) {
+void MethodDescriptorProto::set_output_type(const char* value, size_t size) {
set_has_output_type();
output_type_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.MethodDescriptorProto.output_type)
}
- ::std::string* MethodDescriptorProto::mutable_output_type() {
+::std::string* MethodDescriptorProto::mutable_output_type() {
set_has_output_type();
// @@protoc_insertion_point(field_mutable:google.protobuf.MethodDescriptorProto.output_type)
return output_type_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* MethodDescriptorProto::release_output_type() {
+::std::string* MethodDescriptorProto::release_output_type() {
// @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type)
clear_has_output_type();
return output_type_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) {
+void MethodDescriptorProto::set_allocated_output_type(::std::string* output_type) {
if (output_type != NULL) {
set_has_output_type();
} else {
@@ -7950,7 +8139,8 @@ void MethodDescriptorProto::clear_options() {
}
const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::MethodOptions::internal_default_instance();
}
::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
set_has_options();
@@ -7992,11 +8182,11 @@ void MethodDescriptorProto::clear_client_streaming() {
client_streaming_ = false;
clear_has_client_streaming();
}
- bool MethodDescriptorProto::client_streaming() const {
+bool MethodDescriptorProto::client_streaming() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.client_streaming)
return client_streaming_;
}
- void MethodDescriptorProto::set_client_streaming(bool value) {
+void MethodDescriptorProto::set_client_streaming(bool value) {
set_has_client_streaming();
client_streaming_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.client_streaming)
@@ -8016,16 +8206,19 @@ void MethodDescriptorProto::clear_server_streaming() {
server_streaming_ = false;
clear_has_server_streaming();
}
- bool MethodDescriptorProto::server_streaming() const {
+bool MethodDescriptorProto::server_streaming() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.server_streaming)
return server_streaming_;
}
- void MethodDescriptorProto::set_server_streaming(bool value) {
+void MethodDescriptorProto::set_server_streaming(bool value) {
set_has_server_streaming();
server_streaming_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.server_streaming)
}
+inline const MethodDescriptorProto* MethodDescriptorProto::internal_default_instance() {
+ return &MethodDescriptorProto_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -8035,7 +8228,7 @@ const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor()
return FileOptions_OptimizeMode_descriptor_;
}
bool FileOptions_OptimizeMode_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 1:
case 2:
case 3:
@@ -8073,6 +8266,7 @@ const int FileOptions::kUninterpretedOptionFieldNumber;
FileOptions::FileOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FileOptions)
}
@@ -8084,28 +8278,20 @@ FileOptions::FileOptions(const FileOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions)
}
void FileOptions::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
java_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
java_outer_classname_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- java_multiple_files_ = false;
- java_generate_equals_and_hash_ = false;
- java_string_check_utf8_ = false;
- optimize_for_ = 1;
go_package_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- cc_generic_services_ = false;
- java_generic_services_ = false;
- py_generic_services_ = false;
- deprecated_ = false;
- cc_enable_arenas_ = false;
objc_class_prefix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
csharp_namespace_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&java_multiple_files_, 0, reinterpret_cast<char*>(&cc_enable_arenas_) -
+ reinterpret_cast<char*>(&java_multiple_files_) + sizeof(cc_enable_arenas_));
+ optimize_for_ = 1;
}
FileOptions::~FileOptions() {
@@ -8119,8 +8305,6 @@ void FileOptions::SharedDtor() {
go_package_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
objc_class_prefix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
csharp_namespace_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void FileOptions::SetCachedSize(int size) const {
@@ -8134,11 +8318,11 @@ const ::google::protobuf::Descriptor* FileOptions::descriptor() {
}
const FileOptions& FileOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-FileOptions* FileOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FileOptions> FileOptions_default_instance_;
FileOptions* FileOptions::New(::google::protobuf::Arena* arena) const {
FileOptions* n = new FileOptions;
@@ -8163,7 +8347,7 @@ void FileOptions::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -8194,7 +8378,7 @@ void FileOptions::Clear() {
#undef ZR_
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -8267,10 +8451,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 10: {
if (tag == 80) {
parse_java_multiple_files:
+ set_has_java_multiple_files();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_multiple_files_)));
- set_has_java_multiple_files();
} else {
goto handle_unusual;
}
@@ -8299,10 +8483,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 16: {
if (tag == 128) {
parse_cc_generic_services:
+ set_has_cc_generic_services();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &cc_generic_services_)));
- set_has_cc_generic_services();
} else {
goto handle_unusual;
}
@@ -8314,10 +8498,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 17: {
if (tag == 136) {
parse_java_generic_services:
+ set_has_java_generic_services();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_generic_services_)));
- set_has_java_generic_services();
} else {
goto handle_unusual;
}
@@ -8329,10 +8513,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 18: {
if (tag == 144) {
parse_py_generic_services:
+ set_has_py_generic_services();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &py_generic_services_)));
- set_has_py_generic_services();
} else {
goto handle_unusual;
}
@@ -8340,14 +8524,14 @@ bool FileOptions::MergePartialFromCodedStream(
break;
}
- // optional bool java_generate_equals_and_hash = 20 [default = false];
+ // optional bool java_generate_equals_and_hash = 20 [deprecated = true];
case 20: {
if (tag == 160) {
parse_java_generate_equals_and_hash:
+ set_has_java_generate_equals_and_hash();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_generate_equals_and_hash_)));
- set_has_java_generate_equals_and_hash();
} else {
goto handle_unusual;
}
@@ -8359,10 +8543,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 23: {
if (tag == 184) {
parse_deprecated:
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -8374,10 +8558,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 27: {
if (tag == 216) {
parse_java_string_check_utf8:
+ set_has_java_string_check_utf8();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &java_string_check_utf8_)));
- set_has_java_string_check_utf8();
} else {
goto handle_unusual;
}
@@ -8389,10 +8573,10 @@ bool FileOptions::MergePartialFromCodedStream(
case 31: {
if (tag == 248) {
parse_cc_enable_arenas:
+ set_has_cc_enable_arenas();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &cc_enable_arenas_)));
- set_has_cc_enable_arenas();
} else {
goto handle_unusual;
}
@@ -8459,7 +8643,7 @@ bool FileOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -8537,7 +8721,7 @@ void FileOptions::SerializeWithCachedSizes(
::google::protobuf::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output);
}
- // optional bool java_generate_equals_and_hash = 20 [default = false];
+ // optional bool java_generate_equals_and_hash = 20 [deprecated = true];
if (has_java_generate_equals_and_hash()) {
::google::protobuf::internal::WireFormatLite::WriteBool(20, this->java_generate_equals_and_hash(), output);
}
@@ -8596,6 +8780,7 @@ void FileOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* FileOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FileOptions)
// optional string java_package = 1;
if (has_java_package()) {
@@ -8656,7 +8841,7 @@ void FileOptions::SerializeWithCachedSizes(
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target);
}
- // optional bool java_generate_equals_and_hash = 20 [default = false];
+ // optional bool java_generate_equals_and_hash = 20 [deprecated = true];
if (has_java_generate_equals_and_hash()) {
target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(20, this->java_generate_equals_and_hash(), target);
}
@@ -8717,9 +8902,9 @@ void FileOptions::SerializeWithCachedSizes(
return target;
}
-int FileOptions::ByteSize() const {
+size_t FileOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FileOptions)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 255u) {
// optional string java_package = 1;
@@ -8741,7 +8926,7 @@ int FileOptions::ByteSize() const {
total_size += 1 + 1;
}
- // optional bool java_generate_equals_and_hash = 20 [default = false];
+ // optional bool java_generate_equals_and_hash = 20 [deprecated = true];
if (has_java_generate_equals_and_hash()) {
total_size += 2 + 1;
}
@@ -8807,11 +8992,14 @@ int FileOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -8821,18 +9009,17 @@ int FileOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FileOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FileOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FileOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FileOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const FileOptions>(
&from);
if (source == NULL) {
@@ -8840,15 +9027,21 @@ void FileOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FileOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FileOptions::MergeFrom(const FileOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FileOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void FileOptions::UnsafeMergeFrom(const FileOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_java_package()) {
@@ -8903,7 +9096,8 @@ void FileOptions::MergeFrom(const FileOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -8918,14 +9112,17 @@ void FileOptions::CopyFrom(const FileOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FileOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FileOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void FileOptions::Swap(FileOptions* other) {
@@ -8979,37 +9176,37 @@ void FileOptions::clear_java_package() {
java_package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_java_package();
}
- const ::std::string& FileOptions::java_package() const {
+const ::std::string& FileOptions::java_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_package)
return java_package_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_java_package(const ::std::string& value) {
+void FileOptions::set_java_package(const ::std::string& value) {
set_has_java_package();
java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_package)
}
- void FileOptions::set_java_package(const char* value) {
+void FileOptions::set_java_package(const char* value) {
set_has_java_package();
java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_package)
}
- void FileOptions::set_java_package(const char* value, size_t size) {
+void FileOptions::set_java_package(const char* value, size_t size) {
set_has_java_package();
java_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_package)
}
- ::std::string* FileOptions::mutable_java_package() {
+::std::string* FileOptions::mutable_java_package() {
set_has_java_package();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_package)
return java_package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileOptions::release_java_package() {
+::std::string* FileOptions::release_java_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package)
clear_has_java_package();
return java_package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_allocated_java_package(::std::string* java_package) {
+void FileOptions::set_allocated_java_package(::std::string* java_package) {
if (java_package != NULL) {
set_has_java_package();
} else {
@@ -9033,37 +9230,37 @@ void FileOptions::clear_java_outer_classname() {
java_outer_classname_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_java_outer_classname();
}
- const ::std::string& FileOptions::java_outer_classname() const {
+const ::std::string& FileOptions::java_outer_classname() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_outer_classname)
return java_outer_classname_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_java_outer_classname(const ::std::string& value) {
+void FileOptions::set_java_outer_classname(const ::std::string& value) {
set_has_java_outer_classname();
java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_outer_classname)
}
- void FileOptions::set_java_outer_classname(const char* value) {
+void FileOptions::set_java_outer_classname(const char* value) {
set_has_java_outer_classname();
java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.java_outer_classname)
}
- void FileOptions::set_java_outer_classname(const char* value, size_t size) {
+void FileOptions::set_java_outer_classname(const char* value, size_t size) {
set_has_java_outer_classname();
java_outer_classname_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.java_outer_classname)
}
- ::std::string* FileOptions::mutable_java_outer_classname() {
+::std::string* FileOptions::mutable_java_outer_classname() {
set_has_java_outer_classname();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.java_outer_classname)
return java_outer_classname_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileOptions::release_java_outer_classname() {
+::std::string* FileOptions::release_java_outer_classname() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname)
clear_has_java_outer_classname();
return java_outer_classname_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) {
+void FileOptions::set_allocated_java_outer_classname(::std::string* java_outer_classname) {
if (java_outer_classname != NULL) {
set_has_java_outer_classname();
} else {
@@ -9087,17 +9284,17 @@ void FileOptions::clear_java_multiple_files() {
java_multiple_files_ = false;
clear_has_java_multiple_files();
}
- bool FileOptions::java_multiple_files() const {
+bool FileOptions::java_multiple_files() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_multiple_files)
return java_multiple_files_;
}
- void FileOptions::set_java_multiple_files(bool value) {
+void FileOptions::set_java_multiple_files(bool value) {
set_has_java_multiple_files();
java_multiple_files_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_multiple_files)
}
-// optional bool java_generate_equals_and_hash = 20 [default = false];
+// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
bool FileOptions::has_java_generate_equals_and_hash() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
@@ -9111,11 +9308,11 @@ void FileOptions::clear_java_generate_equals_and_hash() {
java_generate_equals_and_hash_ = false;
clear_has_java_generate_equals_and_hash();
}
- bool FileOptions::java_generate_equals_and_hash() const {
+bool FileOptions::java_generate_equals_and_hash() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generate_equals_and_hash)
return java_generate_equals_and_hash_;
}
- void FileOptions::set_java_generate_equals_and_hash(bool value) {
+void FileOptions::set_java_generate_equals_and_hash(bool value) {
set_has_java_generate_equals_and_hash();
java_generate_equals_and_hash_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generate_equals_and_hash)
@@ -9135,11 +9332,11 @@ void FileOptions::clear_java_string_check_utf8() {
java_string_check_utf8_ = false;
clear_has_java_string_check_utf8();
}
- bool FileOptions::java_string_check_utf8() const {
+bool FileOptions::java_string_check_utf8() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_string_check_utf8)
return java_string_check_utf8_;
}
- void FileOptions::set_java_string_check_utf8(bool value) {
+void FileOptions::set_java_string_check_utf8(bool value) {
set_has_java_string_check_utf8();
java_string_check_utf8_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_string_check_utf8)
@@ -9159,11 +9356,11 @@ void FileOptions::clear_optimize_for() {
optimize_for_ = 1;
clear_has_optimize_for();
}
- ::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for() const {
+::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.optimize_for)
return static_cast< ::google::protobuf::FileOptions_OptimizeMode >(optimize_for_);
}
- void FileOptions::set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value) {
+void FileOptions::set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value) {
assert(::google::protobuf::FileOptions_OptimizeMode_IsValid(value));
set_has_optimize_for();
optimize_for_ = value;
@@ -9184,37 +9381,37 @@ void FileOptions::clear_go_package() {
go_package_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_go_package();
}
- const ::std::string& FileOptions::go_package() const {
+const ::std::string& FileOptions::go_package() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.go_package)
return go_package_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_go_package(const ::std::string& value) {
+void FileOptions::set_go_package(const ::std::string& value) {
set_has_go_package();
go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.go_package)
}
- void FileOptions::set_go_package(const char* value) {
+void FileOptions::set_go_package(const char* value) {
set_has_go_package();
go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.go_package)
}
- void FileOptions::set_go_package(const char* value, size_t size) {
+void FileOptions::set_go_package(const char* value, size_t size) {
set_has_go_package();
go_package_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.go_package)
}
- ::std::string* FileOptions::mutable_go_package() {
+::std::string* FileOptions::mutable_go_package() {
set_has_go_package();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.go_package)
return go_package_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileOptions::release_go_package() {
+::std::string* FileOptions::release_go_package() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package)
clear_has_go_package();
return go_package_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_allocated_go_package(::std::string* go_package) {
+void FileOptions::set_allocated_go_package(::std::string* go_package) {
if (go_package != NULL) {
set_has_go_package();
} else {
@@ -9238,11 +9435,11 @@ void FileOptions::clear_cc_generic_services() {
cc_generic_services_ = false;
clear_has_cc_generic_services();
}
- bool FileOptions::cc_generic_services() const {
+bool FileOptions::cc_generic_services() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_generic_services)
return cc_generic_services_;
}
- void FileOptions::set_cc_generic_services(bool value) {
+void FileOptions::set_cc_generic_services(bool value) {
set_has_cc_generic_services();
cc_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_generic_services)
@@ -9262,11 +9459,11 @@ void FileOptions::clear_java_generic_services() {
java_generic_services_ = false;
clear_has_java_generic_services();
}
- bool FileOptions::java_generic_services() const {
+bool FileOptions::java_generic_services() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generic_services)
return java_generic_services_;
}
- void FileOptions::set_java_generic_services(bool value) {
+void FileOptions::set_java_generic_services(bool value) {
set_has_java_generic_services();
java_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_generic_services)
@@ -9286,11 +9483,11 @@ void FileOptions::clear_py_generic_services() {
py_generic_services_ = false;
clear_has_py_generic_services();
}
- bool FileOptions::py_generic_services() const {
+bool FileOptions::py_generic_services() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.py_generic_services)
return py_generic_services_;
}
- void FileOptions::set_py_generic_services(bool value) {
+void FileOptions::set_py_generic_services(bool value) {
set_has_py_generic_services();
py_generic_services_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.py_generic_services)
@@ -9310,11 +9507,11 @@ void FileOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool FileOptions::deprecated() const {
+bool FileOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.deprecated)
return deprecated_;
}
- void FileOptions::set_deprecated(bool value) {
+void FileOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.deprecated)
@@ -9334,11 +9531,11 @@ void FileOptions::clear_cc_enable_arenas() {
cc_enable_arenas_ = false;
clear_has_cc_enable_arenas();
}
- bool FileOptions::cc_enable_arenas() const {
+bool FileOptions::cc_enable_arenas() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_enable_arenas)
return cc_enable_arenas_;
}
- void FileOptions::set_cc_enable_arenas(bool value) {
+void FileOptions::set_cc_enable_arenas(bool value) {
set_has_cc_enable_arenas();
cc_enable_arenas_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.cc_enable_arenas)
@@ -9358,37 +9555,37 @@ void FileOptions::clear_objc_class_prefix() {
objc_class_prefix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_objc_class_prefix();
}
- const ::std::string& FileOptions::objc_class_prefix() const {
+const ::std::string& FileOptions::objc_class_prefix() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.objc_class_prefix)
return objc_class_prefix_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_objc_class_prefix(const ::std::string& value) {
+void FileOptions::set_objc_class_prefix(const ::std::string& value) {
set_has_objc_class_prefix();
objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.objc_class_prefix)
}
- void FileOptions::set_objc_class_prefix(const char* value) {
+void FileOptions::set_objc_class_prefix(const char* value) {
set_has_objc_class_prefix();
objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.objc_class_prefix)
}
- void FileOptions::set_objc_class_prefix(const char* value, size_t size) {
+void FileOptions::set_objc_class_prefix(const char* value, size_t size) {
set_has_objc_class_prefix();
objc_class_prefix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.objc_class_prefix)
}
- ::std::string* FileOptions::mutable_objc_class_prefix() {
+::std::string* FileOptions::mutable_objc_class_prefix() {
set_has_objc_class_prefix();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.objc_class_prefix)
return objc_class_prefix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileOptions::release_objc_class_prefix() {
+::std::string* FileOptions::release_objc_class_prefix() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix)
clear_has_objc_class_prefix();
return objc_class_prefix_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) {
+void FileOptions::set_allocated_objc_class_prefix(::std::string* objc_class_prefix) {
if (objc_class_prefix != NULL) {
set_has_objc_class_prefix();
} else {
@@ -9412,37 +9609,37 @@ void FileOptions::clear_csharp_namespace() {
csharp_namespace_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_csharp_namespace();
}
- const ::std::string& FileOptions::csharp_namespace() const {
+const ::std::string& FileOptions::csharp_namespace() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileOptions.csharp_namespace)
return csharp_namespace_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_csharp_namespace(const ::std::string& value) {
+void FileOptions::set_csharp_namespace(const ::std::string& value) {
set_has_csharp_namespace();
csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.csharp_namespace)
}
- void FileOptions::set_csharp_namespace(const char* value) {
+void FileOptions::set_csharp_namespace(const char* value) {
set_has_csharp_namespace();
csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.FileOptions.csharp_namespace)
}
- void FileOptions::set_csharp_namespace(const char* value, size_t size) {
+void FileOptions::set_csharp_namespace(const char* value, size_t size) {
set_has_csharp_namespace();
csharp_namespace_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FileOptions.csharp_namespace)
}
- ::std::string* FileOptions::mutable_csharp_namespace() {
+::std::string* FileOptions::mutable_csharp_namespace() {
set_has_csharp_namespace();
// @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.csharp_namespace)
return csharp_namespace_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* FileOptions::release_csharp_namespace() {
+::std::string* FileOptions::release_csharp_namespace() {
// @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace)
clear_has_csharp_namespace();
return csharp_namespace_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) {
+void FileOptions::set_allocated_csharp_namespace(::std::string* csharp_namespace) {
if (csharp_namespace != NULL) {
set_has_csharp_namespace();
} else {
@@ -9482,6 +9679,9 @@ FileOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const FileOptions* FileOptions::internal_default_instance() {
+ return &FileOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -9496,6 +9696,7 @@ const int MessageOptions::kUninterpretedOptionFieldNumber;
MessageOptions::MessageOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MessageOptions)
}
@@ -9507,17 +9708,14 @@ MessageOptions::MessageOptions(const MessageOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.MessageOptions)
}
void MessageOptions::SharedCtor() {
_cached_size_ = 0;
- message_set_wire_format_ = false;
- no_standard_descriptor_accessor_ = false;
- deprecated_ = false;
- map_entry_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&message_set_wire_format_, 0, reinterpret_cast<char*>(&map_entry_) -
+ reinterpret_cast<char*>(&message_set_wire_format_) + sizeof(map_entry_));
}
MessageOptions::~MessageOptions() {
@@ -9526,8 +9724,6 @@ MessageOptions::~MessageOptions() {
}
void MessageOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void MessageOptions::SetCachedSize(int size) const {
@@ -9541,11 +9737,11 @@ const ::google::protobuf::Descriptor* MessageOptions::descriptor() {
}
const MessageOptions& MessageOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-MessageOptions* MessageOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<MessageOptions> MessageOptions_default_instance_;
MessageOptions* MessageOptions::New(::google::protobuf::Arena* arena) const {
MessageOptions* n = new MessageOptions;
@@ -9570,7 +9766,7 @@ void MessageOptions::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -9580,7 +9776,7 @@ void MessageOptions::Clear() {
#undef ZR_
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -9599,10 +9795,10 @@ bool MessageOptions::MergePartialFromCodedStream(
// optional bool message_set_wire_format = 1 [default = false];
case 1: {
if (tag == 8) {
+ set_has_message_set_wire_format();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &message_set_wire_format_)));
- set_has_message_set_wire_format();
} else {
goto handle_unusual;
}
@@ -9614,10 +9810,10 @@ bool MessageOptions::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_no_standard_descriptor_accessor:
+ set_has_no_standard_descriptor_accessor();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &no_standard_descriptor_accessor_)));
- set_has_no_standard_descriptor_accessor();
} else {
goto handle_unusual;
}
@@ -9629,10 +9825,10 @@ bool MessageOptions::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_deprecated:
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -9644,10 +9840,10 @@ bool MessageOptions::MergePartialFromCodedStream(
case 7: {
if (tag == 56) {
parse_map_entry:
+ set_has_map_entry();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &map_entry_)));
- set_has_map_entry();
} else {
goto handle_unusual;
}
@@ -9680,7 +9876,7 @@ bool MessageOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -9741,6 +9937,7 @@ void MessageOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* MessageOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MessageOptions)
// optional bool message_set_wire_format = 1 [default = false];
if (has_message_set_wire_format()) {
@@ -9781,9 +9978,9 @@ void MessageOptions::SerializeWithCachedSizes(
return target;
}
-int MessageOptions::ByteSize() const {
+size_t MessageOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.MessageOptions)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 15u) {
// optional bool message_set_wire_format = 1 [default = false];
@@ -9808,11 +10005,14 @@ int MessageOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -9822,18 +10022,17 @@ int MessageOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MessageOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MessageOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const MessageOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const MessageOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const MessageOptions>(
&from);
if (source == NULL) {
@@ -9841,15 +10040,21 @@ void MessageOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.MessageOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void MessageOptions::MergeFrom(const MessageOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MessageOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void MessageOptions::UnsafeMergeFrom(const MessageOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_message_set_wire_format()) {
@@ -9867,7 +10072,8 @@ void MessageOptions::MergeFrom(const MessageOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -9882,14 +10088,17 @@ void MessageOptions::CopyFrom(const MessageOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.MessageOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool MessageOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void MessageOptions::Swap(MessageOptions* other) {
@@ -9933,11 +10142,11 @@ void MessageOptions::clear_message_set_wire_format() {
message_set_wire_format_ = false;
clear_has_message_set_wire_format();
}
- bool MessageOptions::message_set_wire_format() const {
+bool MessageOptions::message_set_wire_format() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.message_set_wire_format)
return message_set_wire_format_;
}
- void MessageOptions::set_message_set_wire_format(bool value) {
+void MessageOptions::set_message_set_wire_format(bool value) {
set_has_message_set_wire_format();
message_set_wire_format_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.message_set_wire_format)
@@ -9957,11 +10166,11 @@ void MessageOptions::clear_no_standard_descriptor_accessor() {
no_standard_descriptor_accessor_ = false;
clear_has_no_standard_descriptor_accessor();
}
- bool MessageOptions::no_standard_descriptor_accessor() const {
+bool MessageOptions::no_standard_descriptor_accessor() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.no_standard_descriptor_accessor)
return no_standard_descriptor_accessor_;
}
- void MessageOptions::set_no_standard_descriptor_accessor(bool value) {
+void MessageOptions::set_no_standard_descriptor_accessor(bool value) {
set_has_no_standard_descriptor_accessor();
no_standard_descriptor_accessor_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.no_standard_descriptor_accessor)
@@ -9981,11 +10190,11 @@ void MessageOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool MessageOptions::deprecated() const {
+bool MessageOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.deprecated)
return deprecated_;
}
- void MessageOptions::set_deprecated(bool value) {
+void MessageOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.deprecated)
@@ -10005,11 +10214,11 @@ void MessageOptions::clear_map_entry() {
map_entry_ = false;
clear_has_map_entry();
}
- bool MessageOptions::map_entry() const {
+bool MessageOptions::map_entry() const {
// @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.map_entry)
return map_entry_;
}
- void MessageOptions::set_map_entry(bool value) {
+void MessageOptions::set_map_entry(bool value) {
set_has_map_entry();
map_entry_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MessageOptions.map_entry)
@@ -10045,6 +10254,9 @@ MessageOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const MessageOptions* MessageOptions::internal_default_instance() {
+ return &MessageOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -10054,7 +10266,7 @@ const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor() {
return FieldOptions_CType_descriptor_;
}
bool FieldOptions_CType_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 0:
case 1:
case 2:
@@ -10077,7 +10289,7 @@ const ::google::protobuf::EnumDescriptor* FieldOptions_JSType_descriptor() {
return FieldOptions_JSType_descriptor_;
}
bool FieldOptions_JSType_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 0:
case 1:
case 2:
@@ -10107,6 +10319,7 @@ const int FieldOptions::kUninterpretedOptionFieldNumber;
FieldOptions::FieldOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldOptions)
}
@@ -10118,19 +10331,14 @@ FieldOptions::FieldOptions(const FieldOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldOptions)
}
void FieldOptions::SharedCtor() {
_cached_size_ = 0;
- ctype_ = 0;
- packed_ = false;
- jstype_ = 0;
- lazy_ = false;
- deprecated_ = false;
- weak_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&ctype_, 0, reinterpret_cast<char*>(&weak_) -
+ reinterpret_cast<char*>(&ctype_) + sizeof(weak_));
}
FieldOptions::~FieldOptions() {
@@ -10139,8 +10347,6 @@ FieldOptions::~FieldOptions() {
}
void FieldOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void FieldOptions::SetCachedSize(int size) const {
@@ -10154,11 +10360,11 @@ const ::google::protobuf::Descriptor* FieldOptions::descriptor() {
}
const FieldOptions& FieldOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-FieldOptions* FieldOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FieldOptions> FieldOptions_default_instance_;
FieldOptions* FieldOptions::New(::google::protobuf::Arena* arena) const {
FieldOptions* n = new FieldOptions;
@@ -10183,20 +10389,17 @@ void FieldOptions::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
- if (_has_bits_[0 / 32] & 63u) {
- ZR_(ctype_, jstype_);
- ZR_(packed_, weak_);
- }
+ ZR_(ctype_, weak_);
#undef ZR_HELPER_
#undef ZR_
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -10235,10 +10438,10 @@ bool FieldOptions::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_packed:
+ set_has_packed();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &packed_)));
- set_has_packed();
} else {
goto handle_unusual;
}
@@ -10250,10 +10453,10 @@ bool FieldOptions::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_deprecated:
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -10265,10 +10468,10 @@ bool FieldOptions::MergePartialFromCodedStream(
case 5: {
if (tag == 40) {
parse_lazy:
+ set_has_lazy();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &lazy_)));
- set_has_lazy();
} else {
goto handle_unusual;
}
@@ -10300,10 +10503,10 @@ bool FieldOptions::MergePartialFromCodedStream(
case 10: {
if (tag == 80) {
parse_weak:
+ set_has_weak();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &weak_)));
- set_has_weak();
} else {
goto handle_unusual;
}
@@ -10336,7 +10539,7 @@ bool FieldOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -10409,6 +10612,7 @@ void FieldOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* FieldOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldOptions)
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
if (has_ctype()) {
@@ -10461,9 +10665,9 @@ void FieldOptions::SerializeWithCachedSizes(
return target;
}
-int FieldOptions::ByteSize() const {
+size_t FieldOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FieldOptions)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 63u) {
// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING];
@@ -10500,11 +10704,14 @@ int FieldOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -10514,18 +10721,17 @@ int FieldOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FieldOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FieldOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FieldOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const FieldOptions>(
&from);
if (source == NULL) {
@@ -10533,15 +10739,21 @@ void FieldOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FieldOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FieldOptions::MergeFrom(const FieldOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void FieldOptions::UnsafeMergeFrom(const FieldOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_ctype()) {
@@ -10565,7 +10777,8 @@ void FieldOptions::MergeFrom(const FieldOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -10580,14 +10793,17 @@ void FieldOptions::CopyFrom(const FieldOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FieldOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FieldOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void FieldOptions::Swap(FieldOptions* other) {
@@ -10633,11 +10849,11 @@ void FieldOptions::clear_ctype() {
ctype_ = 0;
clear_has_ctype();
}
- ::google::protobuf::FieldOptions_CType FieldOptions::ctype() const {
+::google::protobuf::FieldOptions_CType FieldOptions::ctype() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.ctype)
return static_cast< ::google::protobuf::FieldOptions_CType >(ctype_);
}
- void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value) {
+void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value) {
assert(::google::protobuf::FieldOptions_CType_IsValid(value));
set_has_ctype();
ctype_ = value;
@@ -10658,11 +10874,11 @@ void FieldOptions::clear_packed() {
packed_ = false;
clear_has_packed();
}
- bool FieldOptions::packed() const {
+bool FieldOptions::packed() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.packed)
return packed_;
}
- void FieldOptions::set_packed(bool value) {
+void FieldOptions::set_packed(bool value) {
set_has_packed();
packed_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.packed)
@@ -10682,11 +10898,11 @@ void FieldOptions::clear_jstype() {
jstype_ = 0;
clear_has_jstype();
}
- ::google::protobuf::FieldOptions_JSType FieldOptions::jstype() const {
+::google::protobuf::FieldOptions_JSType FieldOptions::jstype() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.jstype)
return static_cast< ::google::protobuf::FieldOptions_JSType >(jstype_);
}
- void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType value) {
+void FieldOptions::set_jstype(::google::protobuf::FieldOptions_JSType value) {
assert(::google::protobuf::FieldOptions_JSType_IsValid(value));
set_has_jstype();
jstype_ = value;
@@ -10707,11 +10923,11 @@ void FieldOptions::clear_lazy() {
lazy_ = false;
clear_has_lazy();
}
- bool FieldOptions::lazy() const {
+bool FieldOptions::lazy() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.lazy)
return lazy_;
}
- void FieldOptions::set_lazy(bool value) {
+void FieldOptions::set_lazy(bool value) {
set_has_lazy();
lazy_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.lazy)
@@ -10731,11 +10947,11 @@ void FieldOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool FieldOptions::deprecated() const {
+bool FieldOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.deprecated)
return deprecated_;
}
- void FieldOptions::set_deprecated(bool value) {
+void FieldOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.deprecated)
@@ -10755,11 +10971,11 @@ void FieldOptions::clear_weak() {
weak_ = false;
clear_has_weak();
}
- bool FieldOptions::weak() const {
+bool FieldOptions::weak() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.weak)
return weak_;
}
- void FieldOptions::set_weak(bool value) {
+void FieldOptions::set_weak(bool value) {
set_has_weak();
weak_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FieldOptions.weak)
@@ -10795,6 +11011,9 @@ FieldOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const FieldOptions* FieldOptions::internal_default_instance() {
+ return &FieldOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -10805,6 +11024,7 @@ const int OneofOptions::kUninterpretedOptionFieldNumber;
OneofOptions::OneofOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.OneofOptions)
}
@@ -10816,13 +11036,12 @@ OneofOptions::OneofOptions(const OneofOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.OneofOptions)
}
void OneofOptions::SharedCtor() {
_cached_size_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
OneofOptions::~OneofOptions() {
@@ -10831,8 +11050,6 @@ OneofOptions::~OneofOptions() {
}
void OneofOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void OneofOptions::SetCachedSize(int size) const {
@@ -10846,11 +11063,11 @@ const ::google::protobuf::Descriptor* OneofOptions::descriptor() {
}
const OneofOptions& OneofOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-OneofOptions* OneofOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<OneofOptions> OneofOptions_default_instance_;
OneofOptions* OneofOptions::New(::google::protobuf::Arena* arena) const {
OneofOptions* n = new OneofOptions;
@@ -10864,7 +11081,7 @@ void OneofOptions::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.OneofOptions)
_extensions_.Clear();
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -10904,7 +11121,7 @@ bool OneofOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -10945,6 +11162,7 @@ void OneofOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* OneofOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.OneofOptions)
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
for (unsigned int i = 0, n = this->uninterpreted_option_size(); i < n; i++) {
@@ -10965,16 +11183,19 @@ void OneofOptions::SerializeWithCachedSizes(
return target;
}
-int OneofOptions::ByteSize() const {
+size_t OneofOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.OneofOptions)
- int total_size = 0;
+ size_t total_size = 0;
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -10984,18 +11205,17 @@ int OneofOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void OneofOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.OneofOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const OneofOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const OneofOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const OneofOptions>(
&from);
if (source == NULL) {
@@ -11003,19 +11223,26 @@ void OneofOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.OneofOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void OneofOptions::MergeFrom(const OneofOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.OneofOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void OneofOptions::UnsafeMergeFrom(const OneofOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -11030,14 +11257,17 @@ void OneofOptions::CopyFrom(const OneofOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.OneofOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool OneofOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void OneofOptions::Swap(OneofOptions* other) {
@@ -11093,6 +11323,9 @@ OneofOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const OneofOptions* OneofOptions::internal_default_instance() {
+ return &OneofOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -11105,6 +11338,7 @@ const int EnumOptions::kUninterpretedOptionFieldNumber;
EnumOptions::EnumOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumOptions)
}
@@ -11116,15 +11350,14 @@ EnumOptions::EnumOptions(const EnumOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumOptions)
}
void EnumOptions::SharedCtor() {
_cached_size_ = 0;
- allow_alias_ = false;
- deprecated_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&allow_alias_, 0, reinterpret_cast<char*>(&deprecated_) -
+ reinterpret_cast<char*>(&allow_alias_) + sizeof(deprecated_));
}
EnumOptions::~EnumOptions() {
@@ -11133,8 +11366,6 @@ EnumOptions::~EnumOptions() {
}
void EnumOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void EnumOptions::SetCachedSize(int size) const {
@@ -11148,11 +11379,11 @@ const ::google::protobuf::Descriptor* EnumOptions::descriptor() {
}
const EnumOptions& EnumOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-EnumOptions* EnumOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<EnumOptions> EnumOptions_default_instance_;
EnumOptions* EnumOptions::New(::google::protobuf::Arena* arena) const {
EnumOptions* n = new EnumOptions;
@@ -11177,7 +11408,7 @@ void EnumOptions::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -11187,7 +11418,7 @@ void EnumOptions::Clear() {
#undef ZR_
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -11206,10 +11437,10 @@ bool EnumOptions::MergePartialFromCodedStream(
// optional bool allow_alias = 2;
case 2: {
if (tag == 16) {
+ set_has_allow_alias();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &allow_alias_)));
- set_has_allow_alias();
} else {
goto handle_unusual;
}
@@ -11221,10 +11452,10 @@ bool EnumOptions::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_deprecated:
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -11257,7 +11488,7 @@ bool EnumOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -11308,6 +11539,7 @@ void EnumOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* EnumOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumOptions)
// optional bool allow_alias = 2;
if (has_allow_alias()) {
@@ -11338,9 +11570,9 @@ void EnumOptions::SerializeWithCachedSizes(
return target;
}
-int EnumOptions::ByteSize() const {
+size_t EnumOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumOptions)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[0 / 32] & 3u) {
// optional bool allow_alias = 2;
@@ -11355,11 +11587,14 @@ int EnumOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -11369,18 +11604,17 @@ int EnumOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void EnumOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const EnumOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const EnumOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const EnumOptions>(
&from);
if (source == NULL) {
@@ -11388,15 +11622,21 @@ void EnumOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void EnumOptions::MergeFrom(const EnumOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void EnumOptions::UnsafeMergeFrom(const EnumOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_allow_alias()) {
@@ -11408,7 +11648,8 @@ void EnumOptions::MergeFrom(const EnumOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -11423,14 +11664,17 @@ void EnumOptions::CopyFrom(const EnumOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.EnumOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool EnumOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void EnumOptions::Swap(EnumOptions* other) {
@@ -11472,11 +11716,11 @@ void EnumOptions::clear_allow_alias() {
allow_alias_ = false;
clear_has_allow_alias();
}
- bool EnumOptions::allow_alias() const {
+bool EnumOptions::allow_alias() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.allow_alias)
return allow_alias_;
}
- void EnumOptions::set_allow_alias(bool value) {
+void EnumOptions::set_allow_alias(bool value) {
set_has_allow_alias();
allow_alias_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.allow_alias)
@@ -11496,11 +11740,11 @@ void EnumOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool EnumOptions::deprecated() const {
+bool EnumOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.deprecated)
return deprecated_;
}
- void EnumOptions::set_deprecated(bool value) {
+void EnumOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumOptions.deprecated)
@@ -11536,6 +11780,9 @@ EnumOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const EnumOptions* EnumOptions::internal_default_instance() {
+ return &EnumOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -11547,6 +11794,7 @@ const int EnumValueOptions::kUninterpretedOptionFieldNumber;
EnumValueOptions::EnumValueOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValueOptions)
}
@@ -11558,14 +11806,13 @@ EnumValueOptions::EnumValueOptions(const EnumValueOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueOptions)
}
void EnumValueOptions::SharedCtor() {
_cached_size_ = 0;
deprecated_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
EnumValueOptions::~EnumValueOptions() {
@@ -11574,8 +11821,6 @@ EnumValueOptions::~EnumValueOptions() {
}
void EnumValueOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void EnumValueOptions::SetCachedSize(int size) const {
@@ -11589,11 +11834,11 @@ const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() {
}
const EnumValueOptions& EnumValueOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-EnumValueOptions* EnumValueOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<EnumValueOptions> EnumValueOptions_default_instance_;
EnumValueOptions* EnumValueOptions::New(::google::protobuf::Arena* arena) const {
EnumValueOptions* n = new EnumValueOptions;
@@ -11608,7 +11853,7 @@ void EnumValueOptions::Clear() {
_extensions_.Clear();
deprecated_ = false;
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -11627,10 +11872,10 @@ bool EnumValueOptions::MergePartialFromCodedStream(
// optional bool deprecated = 1 [default = false];
case 1: {
if (tag == 8) {
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -11663,7 +11908,7 @@ bool EnumValueOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -11709,6 +11954,7 @@ void EnumValueOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* EnumValueOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValueOptions)
// optional bool deprecated = 1 [default = false];
if (has_deprecated()) {
@@ -11734,9 +11980,9 @@ void EnumValueOptions::SerializeWithCachedSizes(
return target;
}
-int EnumValueOptions::ByteSize() const {
+size_t EnumValueOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumValueOptions)
- int total_size = 0;
+ size_t total_size = 0;
// optional bool deprecated = 1 [default = false];
if (has_deprecated()) {
@@ -11744,11 +11990,14 @@ int EnumValueOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -11758,18 +12007,17 @@ int EnumValueOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void EnumValueOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValueOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const EnumValueOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const EnumValueOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const EnumValueOptions>(
&from);
if (source == NULL) {
@@ -11777,15 +12025,21 @@ void EnumValueOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumValueOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void EnumValueOptions::MergeFrom(const EnumValueOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValueOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void EnumValueOptions::UnsafeMergeFrom(const EnumValueOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_deprecated()) {
@@ -11794,7 +12048,8 @@ void EnumValueOptions::MergeFrom(const EnumValueOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -11809,14 +12064,17 @@ void EnumValueOptions::CopyFrom(const EnumValueOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.EnumValueOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool EnumValueOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void EnumValueOptions::Swap(EnumValueOptions* other) {
@@ -11857,11 +12115,11 @@ void EnumValueOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool EnumValueOptions::deprecated() const {
+bool EnumValueOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.deprecated)
return deprecated_;
}
- void EnumValueOptions::set_deprecated(bool value) {
+void EnumValueOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumValueOptions.deprecated)
@@ -11897,6 +12155,9 @@ EnumValueOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const EnumValueOptions* EnumValueOptions::internal_default_instance() {
+ return &EnumValueOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -11908,6 +12169,7 @@ const int ServiceOptions::kUninterpretedOptionFieldNumber;
ServiceOptions::ServiceOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ServiceOptions)
}
@@ -11919,14 +12181,13 @@ ServiceOptions::ServiceOptions(const ServiceOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceOptions)
}
void ServiceOptions::SharedCtor() {
_cached_size_ = 0;
deprecated_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
ServiceOptions::~ServiceOptions() {
@@ -11935,8 +12196,6 @@ ServiceOptions::~ServiceOptions() {
}
void ServiceOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void ServiceOptions::SetCachedSize(int size) const {
@@ -11950,11 +12209,11 @@ const ::google::protobuf::Descriptor* ServiceOptions::descriptor() {
}
const ServiceOptions& ServiceOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-ServiceOptions* ServiceOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<ServiceOptions> ServiceOptions_default_instance_;
ServiceOptions* ServiceOptions::New(::google::protobuf::Arena* arena) const {
ServiceOptions* n = new ServiceOptions;
@@ -11969,7 +12228,7 @@ void ServiceOptions::Clear() {
_extensions_.Clear();
deprecated_ = false;
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -11988,10 +12247,10 @@ bool ServiceOptions::MergePartialFromCodedStream(
// optional bool deprecated = 33 [default = false];
case 33: {
if (tag == 264) {
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -12024,7 +12283,7 @@ bool ServiceOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -12070,6 +12329,7 @@ void ServiceOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* ServiceOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ServiceOptions)
// optional bool deprecated = 33 [default = false];
if (has_deprecated()) {
@@ -12095,9 +12355,9 @@ void ServiceOptions::SerializeWithCachedSizes(
return target;
}
-int ServiceOptions::ByteSize() const {
+size_t ServiceOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.ServiceOptions)
- int total_size = 0;
+ size_t total_size = 0;
// optional bool deprecated = 33 [default = false];
if (has_deprecated()) {
@@ -12105,11 +12365,14 @@ int ServiceOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -12119,18 +12382,17 @@ int ServiceOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void ServiceOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ServiceOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const ServiceOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const ServiceOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const ServiceOptions>(
&from);
if (source == NULL) {
@@ -12138,15 +12400,21 @@ void ServiceOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ServiceOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void ServiceOptions::MergeFrom(const ServiceOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ServiceOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void ServiceOptions::UnsafeMergeFrom(const ServiceOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_deprecated()) {
@@ -12155,7 +12423,8 @@ void ServiceOptions::MergeFrom(const ServiceOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -12170,14 +12439,17 @@ void ServiceOptions::CopyFrom(const ServiceOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.ServiceOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool ServiceOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void ServiceOptions::Swap(ServiceOptions* other) {
@@ -12218,11 +12490,11 @@ void ServiceOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool ServiceOptions::deprecated() const {
+bool ServiceOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.deprecated)
return deprecated_;
}
- void ServiceOptions::set_deprecated(bool value) {
+void ServiceOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.ServiceOptions.deprecated)
@@ -12258,6 +12530,9 @@ ServiceOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const ServiceOptions* ServiceOptions::internal_default_instance() {
+ return &ServiceOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -12269,6 +12544,7 @@ const int MethodOptions::kUninterpretedOptionFieldNumber;
MethodOptions::MethodOptions()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.MethodOptions)
}
@@ -12280,14 +12556,13 @@ MethodOptions::MethodOptions(const MethodOptions& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.MethodOptions)
}
void MethodOptions::SharedCtor() {
_cached_size_ = 0;
deprecated_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
MethodOptions::~MethodOptions() {
@@ -12296,8 +12571,6 @@ MethodOptions::~MethodOptions() {
}
void MethodOptions::SharedDtor() {
- if (this != default_instance_) {
- }
}
void MethodOptions::SetCachedSize(int size) const {
@@ -12311,11 +12584,11 @@ const ::google::protobuf::Descriptor* MethodOptions::descriptor() {
}
const MethodOptions& MethodOptions::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-MethodOptions* MethodOptions::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<MethodOptions> MethodOptions_default_instance_;
MethodOptions* MethodOptions::New(::google::protobuf::Arena* arena) const {
MethodOptions* n = new MethodOptions;
@@ -12330,7 +12603,7 @@ void MethodOptions::Clear() {
_extensions_.Clear();
deprecated_ = false;
uninterpreted_option_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -12349,10 +12622,10 @@ bool MethodOptions::MergePartialFromCodedStream(
// optional bool deprecated = 33 [default = false];
case 33: {
if (tag == 264) {
+ set_has_deprecated();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &deprecated_)));
- set_has_deprecated();
} else {
goto handle_unusual;
}
@@ -12385,7 +12658,7 @@ bool MethodOptions::MergePartialFromCodedStream(
goto success;
}
if ((8000u <= tag)) {
- DO_(_extensions_.ParseField(tag, input, default_instance_,
+ DO_(_extensions_.ParseField(tag, input, internal_default_instance(),
mutable_unknown_fields()));
continue;
}
@@ -12431,6 +12704,7 @@ void MethodOptions::SerializeWithCachedSizes(
::google::protobuf::uint8* MethodOptions::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.MethodOptions)
// optional bool deprecated = 33 [default = false];
if (has_deprecated()) {
@@ -12456,9 +12730,9 @@ void MethodOptions::SerializeWithCachedSizes(
return target;
}
-int MethodOptions::ByteSize() const {
+size_t MethodOptions::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.MethodOptions)
- int total_size = 0;
+ size_t total_size = 0;
// optional bool deprecated = 33 [default = false];
if (has_deprecated()) {
@@ -12466,11 +12740,14 @@ int MethodOptions::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;
- total_size += 2 * this->uninterpreted_option_size();
- for (int i = 0; i < this->uninterpreted_option_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->uninterpreted_option(i));
+ {
+ unsigned int count = this->uninterpreted_option_size();
+ total_size += 2UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->uninterpreted_option(i));
+ }
}
total_size += _extensions_.ByteSize();
@@ -12480,18 +12757,17 @@ int MethodOptions::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MethodOptions::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.MethodOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const MethodOptions* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const MethodOptions* source =
::google::protobuf::internal::DynamicCastToGenerated<const MethodOptions>(
&from);
if (source == NULL) {
@@ -12499,15 +12775,21 @@ void MethodOptions::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.MethodOptions)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void MethodOptions::MergeFrom(const MethodOptions& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.MethodOptions)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void MethodOptions::UnsafeMergeFrom(const MethodOptions& from) {
+ GOOGLE_DCHECK(&from != this);
uninterpreted_option_.MergeFrom(from.uninterpreted_option_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_deprecated()) {
@@ -12516,7 +12798,8 @@ void MethodOptions::MergeFrom(const MethodOptions& from) {
}
_extensions_.MergeFrom(from._extensions_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -12531,14 +12814,17 @@ void MethodOptions::CopyFrom(const MethodOptions& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.MethodOptions)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool MethodOptions::IsInitialized() const {
if (!::google::protobuf::internal::AllAreInitialized(this->uninterpreted_option())) return false;
- if (!_extensions_.IsInitialized()) return false; return true;
+ if (!_extensions_.IsInitialized()) {
+ return false;
+ }
+ return true;
}
void MethodOptions::Swap(MethodOptions* other) {
@@ -12579,11 +12865,11 @@ void MethodOptions::clear_deprecated() {
deprecated_ = false;
clear_has_deprecated();
}
- bool MethodOptions::deprecated() const {
+bool MethodOptions::deprecated() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.deprecated)
return deprecated_;
}
- void MethodOptions::set_deprecated(bool value) {
+void MethodOptions::set_deprecated(bool value) {
set_has_deprecated();
deprecated_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.MethodOptions.deprecated)
@@ -12619,6 +12905,9 @@ MethodOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const MethodOptions* MethodOptions::internal_default_instance() {
+ return &MethodOptions_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -12630,6 +12919,7 @@ const int UninterpretedOption_NamePart::kIsExtensionFieldNumber;
UninterpretedOption_NamePart::UninterpretedOption_NamePart()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption.NamePart)
}
@@ -12641,16 +12931,14 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOp
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption.NamePart)
}
void UninterpretedOption_NamePart::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
name_part_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
is_extension_ = false;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
UninterpretedOption_NamePart::~UninterpretedOption_NamePart() {
@@ -12660,8 +12948,6 @@ UninterpretedOption_NamePart::~UninterpretedOption_NamePart() {
void UninterpretedOption_NamePart::SharedDtor() {
name_part_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void UninterpretedOption_NamePart::SetCachedSize(int size) const {
@@ -12675,11 +12961,11 @@ const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor()
}
const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-UninterpretedOption_NamePart* UninterpretedOption_NamePart::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption_NamePart> UninterpretedOption_NamePart_default_instance_;
UninterpretedOption_NamePart* UninterpretedOption_NamePart::New(::google::protobuf::Arena* arena) const {
UninterpretedOption_NamePart* n = new UninterpretedOption_NamePart;
@@ -12697,7 +12983,7 @@ void UninterpretedOption_NamePart::Clear() {
}
is_extension_ = false;
}
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -12733,10 +13019,10 @@ bool UninterpretedOption_NamePart::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_is_extension:
+ set_has_is_extension();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &is_extension_)));
- set_has_is_extension();
} else {
goto handle_unusual;
}
@@ -12793,6 +13079,7 @@ void UninterpretedOption_NamePart::SerializeWithCachedSizes(
::google::protobuf::uint8* UninterpretedOption_NamePart::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UninterpretedOption.NamePart)
// required string name_part = 1;
if (has_name_part()) {
@@ -12818,9 +13105,9 @@ void UninterpretedOption_NamePart::SerializeWithCachedSizes(
return target;
}
-int UninterpretedOption_NamePart::RequiredFieldsByteSizeFallback() const {
+size_t UninterpretedOption_NamePart::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:google.protobuf.UninterpretedOption.NamePart)
- int total_size = 0;
+ size_t total_size = 0;
if (has_name_part()) {
// required string name_part = 1;
@@ -12836,9 +13123,9 @@ int UninterpretedOption_NamePart::RequiredFieldsByteSizeFallback() const {
return total_size;
}
-int UninterpretedOption_NamePart::ByteSize() const {
+size_t UninterpretedOption_NamePart::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.UninterpretedOption.NamePart)
- int total_size = 0;
+ size_t total_size = 0;
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required string name_part = 1;
@@ -12857,18 +13144,17 @@ int UninterpretedOption_NamePart::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void UninterpretedOption_NamePart::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UninterpretedOption.NamePart)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const UninterpretedOption_NamePart* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const UninterpretedOption_NamePart* source =
::google::protobuf::internal::DynamicCastToGenerated<const UninterpretedOption_NamePart>(
&from);
if (source == NULL) {
@@ -12876,15 +13162,21 @@ void UninterpretedOption_NamePart::MergeFrom(const ::google::protobuf::Message&
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.UninterpretedOption.NamePart)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption.NamePart)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void UninterpretedOption_NamePart::UnsafeMergeFrom(const UninterpretedOption_NamePart& from) {
+ GOOGLE_DCHECK(&from != this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name_part()) {
set_has_name_part();
@@ -12895,7 +13187,8 @@ void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart&
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -12910,7 +13203,7 @@ void UninterpretedOption_NamePart::CopyFrom(const UninterpretedOption_NamePart&
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.UninterpretedOption.NamePart)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool UninterpretedOption_NamePart::IsInitialized() const {
@@ -12954,6 +13247,7 @@ const int UninterpretedOption::kAggregateValueFieldNumber;
UninterpretedOption::UninterpretedOption()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UninterpretedOption)
}
@@ -12965,20 +13259,17 @@ UninterpretedOption::UninterpretedOption(const UninterpretedOption& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption)
}
void UninterpretedOption::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
identifier_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- positive_int_value_ = GOOGLE_ULONGLONG(0);
- negative_int_value_ = GOOGLE_LONGLONG(0);
- double_value_ = 0;
string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
aggregate_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&positive_int_value_, 0, reinterpret_cast<char*>(&double_value_) -
+ reinterpret_cast<char*>(&positive_int_value_) + sizeof(double_value_));
}
UninterpretedOption::~UninterpretedOption() {
@@ -12990,8 +13281,6 @@ void UninterpretedOption::SharedDtor() {
identifier_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
string_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
aggregate_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void UninterpretedOption::SetCachedSize(int size) const {
@@ -13005,11 +13294,11 @@ const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() {
}
const UninterpretedOption& UninterpretedOption::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-UninterpretedOption* UninterpretedOption::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption> UninterpretedOption_default_instance_;
UninterpretedOption* UninterpretedOption::New(::google::protobuf::Arena* arena) const {
UninterpretedOption* n = new UninterpretedOption;
@@ -13033,7 +13322,7 @@ void UninterpretedOption::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -13054,7 +13343,7 @@ void UninterpretedOption::Clear() {
#undef ZR_
name_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -13107,10 +13396,10 @@ bool UninterpretedOption::MergePartialFromCodedStream(
case 4: {
if (tag == 32) {
parse_positive_int_value:
+ set_has_positive_int_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &positive_int_value_)));
- set_has_positive_int_value();
} else {
goto handle_unusual;
}
@@ -13122,10 +13411,10 @@ bool UninterpretedOption::MergePartialFromCodedStream(
case 5: {
if (tag == 40) {
parse_negative_int_value:
+ set_has_negative_int_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &negative_int_value_)));
- set_has_negative_int_value();
} else {
goto handle_unusual;
}
@@ -13137,10 +13426,10 @@ bool UninterpretedOption::MergePartialFromCodedStream(
case 6: {
if (tag == 49) {
parse_double_value:
+ set_has_double_value();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &double_value_)));
- set_has_double_value();
} else {
goto handle_unusual;
}
@@ -13259,6 +13548,7 @@ void UninterpretedOption::SerializeWithCachedSizes(
::google::protobuf::uint8* UninterpretedOption::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UninterpretedOption)
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
for (unsigned int i = 0, n = this->name_size(); i < n; i++) {
@@ -13319,9 +13609,9 @@ void UninterpretedOption::SerializeWithCachedSizes(
return target;
}
-int UninterpretedOption::ByteSize() const {
+size_t UninterpretedOption::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.UninterpretedOption)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[1 / 32] & 126u) {
// optional string identifier_value = 3;
@@ -13366,11 +13656,14 @@ int UninterpretedOption::ByteSize() const {
}
// repeated .google.protobuf.UninterpretedOption.NamePart name = 2;
- total_size += 1 * this->name_size();
- for (int i = 0; i < this->name_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->name(i));
+ {
+ unsigned int count = this->name_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->name(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -13378,18 +13671,17 @@ int UninterpretedOption::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void UninterpretedOption::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UninterpretedOption)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const UninterpretedOption* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const UninterpretedOption* source =
::google::protobuf::internal::DynamicCastToGenerated<const UninterpretedOption>(
&from);
if (source == NULL) {
@@ -13397,15 +13689,21 @@ void UninterpretedOption::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.UninterpretedOption)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void UninterpretedOption::MergeFrom(const UninterpretedOption& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UninterpretedOption)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void UninterpretedOption::UnsafeMergeFrom(const UninterpretedOption& from) {
+ GOOGLE_DCHECK(&from != this);
name_.MergeFrom(from.name_);
if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) {
if (from.has_identifier_value()) {
@@ -13431,7 +13729,8 @@ void UninterpretedOption::MergeFrom(const UninterpretedOption& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -13446,7 +13745,7 @@ void UninterpretedOption::CopyFrom(const UninterpretedOption& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.UninterpretedOption)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool UninterpretedOption::IsInitialized() const {
@@ -13497,37 +13796,37 @@ void UninterpretedOption_NamePart::clear_name_part() {
name_part_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_name_part();
}
- const ::std::string& UninterpretedOption_NamePart::name_part() const {
+const ::std::string& UninterpretedOption_NamePart::name_part() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.name_part)
return name_part_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) {
+void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) {
set_has_name_part();
name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.name_part)
}
- void UninterpretedOption_NamePart::set_name_part(const char* value) {
+void UninterpretedOption_NamePart::set_name_part(const char* value) {
set_has_name_part();
name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.NamePart.name_part)
}
- void UninterpretedOption_NamePart::set_name_part(const char* value, size_t size) {
+void UninterpretedOption_NamePart::set_name_part(const char* value, size_t size) {
set_has_name_part();
name_part_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.NamePart.name_part)
}
- ::std::string* UninterpretedOption_NamePart::mutable_name_part() {
+::std::string* UninterpretedOption_NamePart::mutable_name_part() {
set_has_name_part();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.NamePart.name_part)
return name_part_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* UninterpretedOption_NamePart::release_name_part() {
+::std::string* UninterpretedOption_NamePart::release_name_part() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part)
clear_has_name_part();
return name_part_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) {
+void UninterpretedOption_NamePart::set_allocated_name_part(::std::string* name_part) {
if (name_part != NULL) {
set_has_name_part();
} else {
@@ -13551,16 +13850,19 @@ void UninterpretedOption_NamePart::clear_is_extension() {
is_extension_ = false;
clear_has_is_extension();
}
- bool UninterpretedOption_NamePart::is_extension() const {
+bool UninterpretedOption_NamePart::is_extension() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.is_extension)
return is_extension_;
}
- void UninterpretedOption_NamePart::set_is_extension(bool value) {
+void UninterpretedOption_NamePart::set_is_extension(bool value) {
set_has_is_extension();
is_extension_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.is_extension)
}
+inline const UninterpretedOption_NamePart* UninterpretedOption_NamePart::internal_default_instance() {
+ return &UninterpretedOption_NamePart_default_instance_.get();
+}
// -------------------------------------------------------------------
// UninterpretedOption
@@ -13609,37 +13911,37 @@ void UninterpretedOption::clear_identifier_value() {
identifier_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_identifier_value();
}
- const ::std::string& UninterpretedOption::identifier_value() const {
+const ::std::string& UninterpretedOption::identifier_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.identifier_value)
return identifier_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption::set_identifier_value(const ::std::string& value) {
+void UninterpretedOption::set_identifier_value(const ::std::string& value) {
set_has_identifier_value();
identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.identifier_value)
}
- void UninterpretedOption::set_identifier_value(const char* value) {
+void UninterpretedOption::set_identifier_value(const char* value) {
set_has_identifier_value();
identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.identifier_value)
}
- void UninterpretedOption::set_identifier_value(const char* value, size_t size) {
+void UninterpretedOption::set_identifier_value(const char* value, size_t size) {
set_has_identifier_value();
identifier_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.identifier_value)
}
- ::std::string* UninterpretedOption::mutable_identifier_value() {
+::std::string* UninterpretedOption::mutable_identifier_value() {
set_has_identifier_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.identifier_value)
return identifier_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* UninterpretedOption::release_identifier_value() {
+::std::string* UninterpretedOption::release_identifier_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value)
clear_has_identifier_value();
return identifier_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) {
+void UninterpretedOption::set_allocated_identifier_value(::std::string* identifier_value) {
if (identifier_value != NULL) {
set_has_identifier_value();
} else {
@@ -13663,11 +13965,11 @@ void UninterpretedOption::clear_positive_int_value() {
positive_int_value_ = GOOGLE_ULONGLONG(0);
clear_has_positive_int_value();
}
- ::google::protobuf::uint64 UninterpretedOption::positive_int_value() const {
+::google::protobuf::uint64 UninterpretedOption::positive_int_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.positive_int_value)
return positive_int_value_;
}
- void UninterpretedOption::set_positive_int_value(::google::protobuf::uint64 value) {
+void UninterpretedOption::set_positive_int_value(::google::protobuf::uint64 value) {
set_has_positive_int_value();
positive_int_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.positive_int_value)
@@ -13687,11 +13989,11 @@ void UninterpretedOption::clear_negative_int_value() {
negative_int_value_ = GOOGLE_LONGLONG(0);
clear_has_negative_int_value();
}
- ::google::protobuf::int64 UninterpretedOption::negative_int_value() const {
+::google::protobuf::int64 UninterpretedOption::negative_int_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.negative_int_value)
return negative_int_value_;
}
- void UninterpretedOption::set_negative_int_value(::google::protobuf::int64 value) {
+void UninterpretedOption::set_negative_int_value(::google::protobuf::int64 value) {
set_has_negative_int_value();
negative_int_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.negative_int_value)
@@ -13711,11 +14013,11 @@ void UninterpretedOption::clear_double_value() {
double_value_ = 0;
clear_has_double_value();
}
- double UninterpretedOption::double_value() const {
+double UninterpretedOption::double_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.double_value)
return double_value_;
}
- void UninterpretedOption::set_double_value(double value) {
+void UninterpretedOption::set_double_value(double value) {
set_has_double_value();
double_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.double_value)
@@ -13735,37 +14037,37 @@ void UninterpretedOption::clear_string_value() {
string_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_string_value();
}
- const ::std::string& UninterpretedOption::string_value() const {
+const ::std::string& UninterpretedOption::string_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.string_value)
return string_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption::set_string_value(const ::std::string& value) {
+void UninterpretedOption::set_string_value(const ::std::string& value) {
set_has_string_value();
string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.string_value)
}
- void UninterpretedOption::set_string_value(const char* value) {
+void UninterpretedOption::set_string_value(const char* value) {
set_has_string_value();
string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.string_value)
}
- void UninterpretedOption::set_string_value(const void* value, size_t size) {
+void UninterpretedOption::set_string_value(const void* value, size_t size) {
set_has_string_value();
string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.string_value)
}
- ::std::string* UninterpretedOption::mutable_string_value() {
+::std::string* UninterpretedOption::mutable_string_value() {
set_has_string_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.string_value)
return string_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* UninterpretedOption::release_string_value() {
+::std::string* UninterpretedOption::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value)
clear_has_string_value();
return string_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption::set_allocated_string_value(::std::string* string_value) {
+void UninterpretedOption::set_allocated_string_value(::std::string* string_value) {
if (string_value != NULL) {
set_has_string_value();
} else {
@@ -13789,37 +14091,37 @@ void UninterpretedOption::clear_aggregate_value() {
aggregate_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_aggregate_value();
}
- const ::std::string& UninterpretedOption::aggregate_value() const {
+const ::std::string& UninterpretedOption::aggregate_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.aggregate_value)
return aggregate_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption::set_aggregate_value(const ::std::string& value) {
+void UninterpretedOption::set_aggregate_value(const ::std::string& value) {
set_has_aggregate_value();
aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.aggregate_value)
}
- void UninterpretedOption::set_aggregate_value(const char* value) {
+void UninterpretedOption::set_aggregate_value(const char* value) {
set_has_aggregate_value();
aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.UninterpretedOption.aggregate_value)
}
- void UninterpretedOption::set_aggregate_value(const char* value, size_t size) {
+void UninterpretedOption::set_aggregate_value(const char* value, size_t size) {
set_has_aggregate_value();
aggregate_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.UninterpretedOption.aggregate_value)
}
- ::std::string* UninterpretedOption::mutable_aggregate_value() {
+::std::string* UninterpretedOption::mutable_aggregate_value() {
set_has_aggregate_value();
// @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.aggregate_value)
return aggregate_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* UninterpretedOption::release_aggregate_value() {
+::std::string* UninterpretedOption::release_aggregate_value() {
// @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value)
clear_has_aggregate_value();
return aggregate_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) {
+void UninterpretedOption::set_allocated_aggregate_value(::std::string* aggregate_value) {
if (aggregate_value != NULL) {
set_has_aggregate_value();
} else {
@@ -13829,6 +14131,9 @@ void UninterpretedOption::clear_aggregate_value() {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
}
+inline const UninterpretedOption* UninterpretedOption::internal_default_instance() {
+ return &UninterpretedOption_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -13843,6 +14148,7 @@ const int SourceCodeInfo_Location::kLeadingDetachedCommentsFieldNumber;
SourceCodeInfo_Location::SourceCodeInfo_Location()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo.Location)
}
@@ -13854,16 +14160,14 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location&
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo.Location)
}
void SourceCodeInfo_Location::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
leading_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
trailing_comments_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
SourceCodeInfo_Location::~SourceCodeInfo_Location() {
@@ -13874,8 +14178,6 @@ SourceCodeInfo_Location::~SourceCodeInfo_Location() {
void SourceCodeInfo_Location::SharedDtor() {
leading_comments_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
trailing_comments_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void SourceCodeInfo_Location::SetCachedSize(int size) const {
@@ -13889,11 +14191,11 @@ const ::google::protobuf::Descriptor* SourceCodeInfo_Location::descriptor() {
}
const SourceCodeInfo_Location& SourceCodeInfo_Location::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-SourceCodeInfo_Location* SourceCodeInfo_Location::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo_Location> SourceCodeInfo_Location_default_instance_;
SourceCodeInfo_Location* SourceCodeInfo_Location::New(::google::protobuf::Arena* arena) const {
SourceCodeInfo_Location* n = new SourceCodeInfo_Location;
@@ -13916,7 +14218,7 @@ void SourceCodeInfo_Location::Clear() {
path_.Clear();
span_.Clear();
leading_detached_comments_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -14104,6 +14406,7 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
::google::protobuf::uint8* SourceCodeInfo_Location::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceCodeInfo.Location)
// repeated int32 path = 1 [packed = true];
if (this->path_size() > 0) {
@@ -14173,9 +14476,9 @@ void SourceCodeInfo_Location::SerializeWithCachedSizes(
return target;
}
-int SourceCodeInfo_Location::ByteSize() const {
+size_t SourceCodeInfo_Location::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.SourceCodeInfo.Location)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[2 / 32] & 12u) {
// optional string leading_comments = 3;
@@ -14195,8 +14498,9 @@ int SourceCodeInfo_Location::ByteSize() const {
}
// repeated int32 path = 1 [packed = true];
{
- int data_size = 0;
- for (int i = 0; i < this->path_size(); i++) {
+ size_t data_size = 0;
+ unsigned int count = this->path_size();
+ for (unsigned int i = 0; i < count; i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int32Size(this->path(i));
}
@@ -14204,16 +14508,18 @@ int SourceCodeInfo_Location::ByteSize() const {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _path_cached_byte_size_ = data_size;
+ _path_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
// repeated int32 span = 2 [packed = true];
{
- int data_size = 0;
- for (int i = 0; i < this->span_size(); i++) {
+ size_t data_size = 0;
+ unsigned int count = this->span_size();
+ for (unsigned int i = 0; i < count; i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int32Size(this->span(i));
}
@@ -14221,14 +14527,16 @@ int SourceCodeInfo_Location::ByteSize() const {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _span_cached_byte_size_ = data_size;
+ _span_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
// repeated string leading_detached_comments = 6;
- total_size += 1 * this->leading_detached_comments_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->leading_detached_comments_size());
for (int i = 0; i < this->leading_detached_comments_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->leading_detached_comments(i));
@@ -14239,18 +14547,17 @@ int SourceCodeInfo_Location::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SourceCodeInfo_Location::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceCodeInfo.Location)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const SourceCodeInfo_Location* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const SourceCodeInfo_Location* source =
::google::protobuf::internal::DynamicCastToGenerated<const SourceCodeInfo_Location>(
&from);
if (source == NULL) {
@@ -14258,18 +14565,24 @@ void SourceCodeInfo_Location::MergeFrom(const ::google::protobuf::Message& from)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceCodeInfo.Location)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo.Location)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
- path_.MergeFrom(from.path_);
- span_.MergeFrom(from.span_);
- leading_detached_comments_.MergeFrom(from.leading_detached_comments_);
+}
+
+void SourceCodeInfo_Location::UnsafeMergeFrom(const SourceCodeInfo_Location& from) {
+ GOOGLE_DCHECK(&from != this);
+ path_.UnsafeMergeFrom(from.path_);
+ span_.UnsafeMergeFrom(from.span_);
+ leading_detached_comments_.UnsafeMergeFrom(from.leading_detached_comments_);
if (from._has_bits_[2 / 32] & (0xffu << (2 % 32))) {
if (from.has_leading_comments()) {
set_has_leading_comments();
@@ -14281,7 +14594,8 @@ void SourceCodeInfo_Location::MergeFrom(const SourceCodeInfo_Location& from) {
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -14296,7 +14610,7 @@ void SourceCodeInfo_Location::CopyFrom(const SourceCodeInfo_Location& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.SourceCodeInfo.Location)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool SourceCodeInfo_Location::IsInitialized() const {
@@ -14336,6 +14650,7 @@ const int SourceCodeInfo::kLocationFieldNumber;
SourceCodeInfo::SourceCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceCodeInfo)
}
@@ -14347,13 +14662,12 @@ SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo)
}
void SourceCodeInfo::SharedCtor() {
_cached_size_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
SourceCodeInfo::~SourceCodeInfo() {
@@ -14362,8 +14676,6 @@ SourceCodeInfo::~SourceCodeInfo() {
}
void SourceCodeInfo::SharedDtor() {
- if (this != default_instance_) {
- }
}
void SourceCodeInfo::SetCachedSize(int size) const {
@@ -14377,11 +14689,11 @@ const ::google::protobuf::Descriptor* SourceCodeInfo::descriptor() {
}
const SourceCodeInfo& SourceCodeInfo::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-SourceCodeInfo* SourceCodeInfo::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo> SourceCodeInfo_default_instance_;
SourceCodeInfo* SourceCodeInfo::New(::google::protobuf::Arena* arena) const {
SourceCodeInfo* n = new SourceCodeInfo;
@@ -14394,7 +14706,7 @@ SourceCodeInfo* SourceCodeInfo::New(::google::protobuf::Arena* arena) const {
void SourceCodeInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.SourceCodeInfo)
location_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -14466,6 +14778,7 @@ void SourceCodeInfo::SerializeWithCachedSizes(
::google::protobuf::uint8* SourceCodeInfo::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceCodeInfo)
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
for (unsigned int i = 0, n = this->location_size(); i < n; i++) {
@@ -14482,16 +14795,19 @@ void SourceCodeInfo::SerializeWithCachedSizes(
return target;
}
-int SourceCodeInfo::ByteSize() const {
+size_t SourceCodeInfo::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.SourceCodeInfo)
- int total_size = 0;
+ size_t total_size = 0;
// repeated .google.protobuf.SourceCodeInfo.Location location = 1;
- total_size += 1 * this->location_size();
- for (int i = 0; i < this->location_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->location(i));
+ {
+ unsigned int count = this->location_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->location(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -14499,18 +14815,17 @@ int SourceCodeInfo::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SourceCodeInfo::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceCodeInfo)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const SourceCodeInfo* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const SourceCodeInfo* source =
::google::protobuf::internal::DynamicCastToGenerated<const SourceCodeInfo>(
&from);
if (source == NULL) {
@@ -14518,18 +14833,25 @@ void SourceCodeInfo::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceCodeInfo)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void SourceCodeInfo::MergeFrom(const SourceCodeInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceCodeInfo)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void SourceCodeInfo::UnsafeMergeFrom(const SourceCodeInfo& from) {
+ GOOGLE_DCHECK(&from != this);
location_.MergeFrom(from.location_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -14544,7 +14866,7 @@ void SourceCodeInfo::CopyFrom(const SourceCodeInfo& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.SourceCodeInfo)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool SourceCodeInfo::IsInitialized() const {
@@ -14581,24 +14903,24 @@ int SourceCodeInfo_Location::path_size() const {
void SourceCodeInfo_Location::clear_path() {
path_.Clear();
}
- ::google::protobuf::int32 SourceCodeInfo_Location::path(int index) const {
+::google::protobuf::int32 SourceCodeInfo_Location::path(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.path)
return path_.Get(index);
}
- void SourceCodeInfo_Location::set_path(int index, ::google::protobuf::int32 value) {
+void SourceCodeInfo_Location::set_path(int index, ::google::protobuf::int32 value) {
path_.Set(index, value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.path)
}
- void SourceCodeInfo_Location::add_path(::google::protobuf::int32 value) {
+void SourceCodeInfo_Location::add_path(::google::protobuf::int32 value) {
path_.Add(value);
// @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.path)
}
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
SourceCodeInfo_Location::path() const {
// @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.path)
return path_;
}
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
SourceCodeInfo_Location::mutable_path() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.path)
return &path_;
@@ -14611,24 +14933,24 @@ int SourceCodeInfo_Location::span_size() const {
void SourceCodeInfo_Location::clear_span() {
span_.Clear();
}
- ::google::protobuf::int32 SourceCodeInfo_Location::span(int index) const {
+::google::protobuf::int32 SourceCodeInfo_Location::span(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.span)
return span_.Get(index);
}
- void SourceCodeInfo_Location::set_span(int index, ::google::protobuf::int32 value) {
+void SourceCodeInfo_Location::set_span(int index, ::google::protobuf::int32 value) {
span_.Set(index, value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.span)
}
- void SourceCodeInfo_Location::add_span(::google::protobuf::int32 value) {
+void SourceCodeInfo_Location::add_span(::google::protobuf::int32 value) {
span_.Add(value);
// @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.span)
}
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
SourceCodeInfo_Location::span() const {
// @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.span)
return span_;
}
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
SourceCodeInfo_Location::mutable_span() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.span)
return &span_;
@@ -14648,37 +14970,37 @@ void SourceCodeInfo_Location::clear_leading_comments() {
leading_comments_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_leading_comments();
}
- const ::std::string& SourceCodeInfo_Location::leading_comments() const {
+const ::std::string& SourceCodeInfo_Location::leading_comments() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_comments)
return leading_comments_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void SourceCodeInfo_Location::set_leading_comments(const ::std::string& value) {
+void SourceCodeInfo_Location::set_leading_comments(const ::std::string& value) {
set_has_leading_comments();
leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
- void SourceCodeInfo_Location::set_leading_comments(const char* value) {
+void SourceCodeInfo_Location::set_leading_comments(const char* value) {
set_has_leading_comments();
leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
- void SourceCodeInfo_Location::set_leading_comments(const char* value, size_t size) {
+void SourceCodeInfo_Location::set_leading_comments(const char* value, size_t size) {
set_has_leading_comments();
leading_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_comments)
}
- ::std::string* SourceCodeInfo_Location::mutable_leading_comments() {
+::std::string* SourceCodeInfo_Location::mutable_leading_comments() {
set_has_leading_comments();
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_comments)
return leading_comments_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* SourceCodeInfo_Location::release_leading_comments() {
+::std::string* SourceCodeInfo_Location::release_leading_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments)
clear_has_leading_comments();
return leading_comments_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) {
+void SourceCodeInfo_Location::set_allocated_leading_comments(::std::string* leading_comments) {
if (leading_comments != NULL) {
set_has_leading_comments();
} else {
@@ -14702,37 +15024,37 @@ void SourceCodeInfo_Location::clear_trailing_comments() {
trailing_comments_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_trailing_comments();
}
- const ::std::string& SourceCodeInfo_Location::trailing_comments() const {
+const ::std::string& SourceCodeInfo_Location::trailing_comments() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.trailing_comments)
return trailing_comments_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void SourceCodeInfo_Location::set_trailing_comments(const ::std::string& value) {
+void SourceCodeInfo_Location::set_trailing_comments(const ::std::string& value) {
set_has_trailing_comments();
trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
- void SourceCodeInfo_Location::set_trailing_comments(const char* value) {
+void SourceCodeInfo_Location::set_trailing_comments(const char* value) {
set_has_trailing_comments();
trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
- void SourceCodeInfo_Location::set_trailing_comments(const char* value, size_t size) {
+void SourceCodeInfo_Location::set_trailing_comments(const char* value, size_t size) {
set_has_trailing_comments();
trailing_comments_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.trailing_comments)
}
- ::std::string* SourceCodeInfo_Location::mutable_trailing_comments() {
+::std::string* SourceCodeInfo_Location::mutable_trailing_comments() {
set_has_trailing_comments();
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.trailing_comments)
return trailing_comments_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* SourceCodeInfo_Location::release_trailing_comments() {
+::std::string* SourceCodeInfo_Location::release_trailing_comments() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments)
clear_has_trailing_comments();
return trailing_comments_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) {
+void SourceCodeInfo_Location::set_allocated_trailing_comments(::std::string* trailing_comments) {
if (trailing_comments != NULL) {
set_has_trailing_comments();
} else {
@@ -14749,54 +15071,57 @@ int SourceCodeInfo_Location::leading_detached_comments_size() const {
void SourceCodeInfo_Location::clear_leading_detached_comments() {
leading_detached_comments_.Clear();
}
- const ::std::string& SourceCodeInfo_Location::leading_detached_comments(int index) const {
+const ::std::string& SourceCodeInfo_Location::leading_detached_comments(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
return leading_detached_comments_.Get(index);
}
- ::std::string* SourceCodeInfo_Location::mutable_leading_detached_comments(int index) {
+::std::string* SourceCodeInfo_Location::mutable_leading_detached_comments(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
return leading_detached_comments_.Mutable(index);
}
- void SourceCodeInfo_Location::set_leading_detached_comments(int index, const ::std::string& value) {
+void SourceCodeInfo_Location::set_leading_detached_comments(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
leading_detached_comments_.Mutable(index)->assign(value);
}
- void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value) {
+void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value) {
leading_detached_comments_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
- void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value, size_t size) {
+void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value, size_t size) {
leading_detached_comments_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
- ::std::string* SourceCodeInfo_Location::add_leading_detached_comments() {
+::std::string* SourceCodeInfo_Location::add_leading_detached_comments() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
return leading_detached_comments_.Add();
}
- void SourceCodeInfo_Location::add_leading_detached_comments(const ::std::string& value) {
+void SourceCodeInfo_Location::add_leading_detached_comments(const ::std::string& value) {
leading_detached_comments_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
- void SourceCodeInfo_Location::add_leading_detached_comments(const char* value) {
+void SourceCodeInfo_Location::add_leading_detached_comments(const char* value) {
leading_detached_comments_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
- void SourceCodeInfo_Location::add_leading_detached_comments(const char* value, size_t size) {
+void SourceCodeInfo_Location::add_leading_detached_comments(const char* value, size_t size) {
leading_detached_comments_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
}
- const ::google::protobuf::RepeatedPtrField< ::std::string>&
+const ::google::protobuf::RepeatedPtrField< ::std::string>&
SourceCodeInfo_Location::leading_detached_comments() const {
// @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
return leading_detached_comments_;
}
- ::google::protobuf::RepeatedPtrField< ::std::string>*
+::google::protobuf::RepeatedPtrField< ::std::string>*
SourceCodeInfo_Location::mutable_leading_detached_comments() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments)
return &leading_detached_comments_;
}
+inline const SourceCodeInfo_Location* SourceCodeInfo_Location::internal_default_instance() {
+ return &SourceCodeInfo_Location_default_instance_.get();
+}
// -------------------------------------------------------------------
// SourceCodeInfo
@@ -14831,6 +15156,9 @@ SourceCodeInfo::location() const {
return location_;
}
+inline const SourceCodeInfo* SourceCodeInfo::internal_default_instance() {
+ return &SourceCodeInfo_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -14844,6 +15172,7 @@ const int GeneratedCodeInfo_Annotation::kEndFieldNumber;
GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo.Annotation)
}
@@ -14855,17 +15184,15 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeIn
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo.Annotation)
}
void GeneratedCodeInfo_Annotation::SharedCtor() {
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
source_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- begin_ = 0;
- end_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ ::memset(&begin_, 0, reinterpret_cast<char*>(&end_) -
+ reinterpret_cast<char*>(&begin_) + sizeof(end_));
}
GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() {
@@ -14875,8 +15202,6 @@ GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() {
void GeneratedCodeInfo_Annotation::SharedDtor() {
source_file_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const {
@@ -14890,11 +15215,11 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo_Annotation::descriptor()
}
const GeneratedCodeInfo_Annotation& GeneratedCodeInfo_Annotation::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-GeneratedCodeInfo_Annotation* GeneratedCodeInfo_Annotation::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo_Annotation> GeneratedCodeInfo_Annotation_default_instance_;
GeneratedCodeInfo_Annotation* GeneratedCodeInfo_Annotation::New(::google::protobuf::Arena* arena) const {
GeneratedCodeInfo_Annotation* n = new GeneratedCodeInfo_Annotation;
@@ -14918,7 +15243,7 @@ void GeneratedCodeInfo_Annotation::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -14933,7 +15258,7 @@ void GeneratedCodeInfo_Annotation::Clear() {
#undef ZR_
path_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -14987,10 +15312,10 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_begin:
+ set_has_begin();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &begin_)));
- set_has_begin();
} else {
goto handle_unusual;
}
@@ -15002,10 +15327,10 @@ bool GeneratedCodeInfo_Annotation::MergePartialFromCodedStream(
case 4: {
if (tag == 32) {
parse_end:
+ set_has_end();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &end_)));
- set_has_end();
} else {
goto handle_unusual;
}
@@ -15077,6 +15402,7 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
::google::protobuf::uint8* GeneratedCodeInfo_Annotation::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.GeneratedCodeInfo.Annotation)
// repeated int32 path = 1 [packed = true];
if (this->path_size() > 0) {
@@ -15121,9 +15447,9 @@ void GeneratedCodeInfo_Annotation::SerializeWithCachedSizes(
return target;
}
-int GeneratedCodeInfo_Annotation::ByteSize() const {
+size_t GeneratedCodeInfo_Annotation::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.GeneratedCodeInfo.Annotation)
- int total_size = 0;
+ size_t total_size = 0;
if (_has_bits_[1 / 32] & 14u) {
// optional string source_file = 2;
@@ -15150,8 +15476,9 @@ int GeneratedCodeInfo_Annotation::ByteSize() const {
}
// repeated int32 path = 1 [packed = true];
{
- int data_size = 0;
- for (int i = 0; i < this->path_size(); i++) {
+ size_t data_size = 0;
+ unsigned int count = this->path_size();
+ for (unsigned int i = 0; i < count; i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int32Size(this->path(i));
}
@@ -15159,8 +15486,9 @@ int GeneratedCodeInfo_Annotation::ByteSize() const {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _path_cached_byte_size_ = data_size;
+ _path_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
@@ -15170,18 +15498,17 @@ int GeneratedCodeInfo_Annotation::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void GeneratedCodeInfo_Annotation::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const GeneratedCodeInfo_Annotation* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const GeneratedCodeInfo_Annotation* source =
::google::protobuf::internal::DynamicCastToGenerated<const GeneratedCodeInfo_Annotation>(
&from);
if (source == NULL) {
@@ -15189,16 +15516,22 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const ::google::protobuf::Message&
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.GeneratedCodeInfo.Annotation)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo.Annotation)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
- path_.MergeFrom(from.path_);
+}
+
+void GeneratedCodeInfo_Annotation::UnsafeMergeFrom(const GeneratedCodeInfo_Annotation& from) {
+ GOOGLE_DCHECK(&from != this);
+ path_.UnsafeMergeFrom(from.path_);
if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) {
if (from.has_source_file()) {
set_has_source_file();
@@ -15212,7 +15545,8 @@ void GeneratedCodeInfo_Annotation::MergeFrom(const GeneratedCodeInfo_Annotation&
}
}
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -15227,7 +15561,7 @@ void GeneratedCodeInfo_Annotation::CopyFrom(const GeneratedCodeInfo_Annotation&
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.GeneratedCodeInfo.Annotation)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool GeneratedCodeInfo_Annotation::IsInitialized() const {
@@ -15266,6 +15600,7 @@ const int GeneratedCodeInfo::kAnnotationFieldNumber;
GeneratedCodeInfo::GeneratedCodeInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.GeneratedCodeInfo)
}
@@ -15277,13 +15612,12 @@ GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo)
}
void GeneratedCodeInfo::SharedCtor() {
_cached_size_ = 0;
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
}
GeneratedCodeInfo::~GeneratedCodeInfo() {
@@ -15292,8 +15626,6 @@ GeneratedCodeInfo::~GeneratedCodeInfo() {
}
void GeneratedCodeInfo::SharedDtor() {
- if (this != default_instance_) {
- }
}
void GeneratedCodeInfo::SetCachedSize(int size) const {
@@ -15307,11 +15639,11 @@ const ::google::protobuf::Descriptor* GeneratedCodeInfo::descriptor() {
}
const GeneratedCodeInfo& GeneratedCodeInfo::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
+ return *internal_default_instance();
}
-GeneratedCodeInfo* GeneratedCodeInfo::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo> GeneratedCodeInfo_default_instance_;
GeneratedCodeInfo* GeneratedCodeInfo::New(::google::protobuf::Arena* arena) const {
GeneratedCodeInfo* n = new GeneratedCodeInfo;
@@ -15324,7 +15656,7 @@ GeneratedCodeInfo* GeneratedCodeInfo::New(::google::protobuf::Arena* arena) cons
void GeneratedCodeInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.GeneratedCodeInfo)
annotation_.Clear();
- ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ _has_bits_.Clear();
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
@@ -15396,6 +15728,7 @@ void GeneratedCodeInfo::SerializeWithCachedSizes(
::google::protobuf::uint8* GeneratedCodeInfo::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.GeneratedCodeInfo)
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
for (unsigned int i = 0, n = this->annotation_size(); i < n; i++) {
@@ -15412,16 +15745,19 @@ void GeneratedCodeInfo::SerializeWithCachedSizes(
return target;
}
-int GeneratedCodeInfo::ByteSize() const {
+size_t GeneratedCodeInfo::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.GeneratedCodeInfo)
- int total_size = 0;
+ size_t total_size = 0;
// repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
- total_size += 1 * this->annotation_size();
- for (int i = 0; i < this->annotation_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->annotation(i));
+ {
+ unsigned int count = this->annotation_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->annotation(i));
+ }
}
if (_internal_metadata_.have_unknown_fields()) {
@@ -15429,18 +15765,17 @@ int GeneratedCodeInfo::ByteSize() const {
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void GeneratedCodeInfo::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.GeneratedCodeInfo)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const GeneratedCodeInfo* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const GeneratedCodeInfo* source =
::google::protobuf::internal::DynamicCastToGenerated<const GeneratedCodeInfo>(
&from);
if (source == NULL) {
@@ -15448,18 +15783,25 @@ void GeneratedCodeInfo::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.GeneratedCodeInfo)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void GeneratedCodeInfo::MergeFrom(const GeneratedCodeInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.GeneratedCodeInfo)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void GeneratedCodeInfo::UnsafeMergeFrom(const GeneratedCodeInfo& from) {
+ GOOGLE_DCHECK(&from != this);
annotation_.MergeFrom(from.annotation_);
if (from._internal_metadata_.have_unknown_fields()) {
- mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+ ::google::protobuf::UnknownFieldSet::MergeToInternalMetdata(
+ from.unknown_fields(), &_internal_metadata_);
}
}
@@ -15474,7 +15816,7 @@ void GeneratedCodeInfo::CopyFrom(const GeneratedCodeInfo& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.GeneratedCodeInfo)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool GeneratedCodeInfo::IsInitialized() const {
@@ -15511,24 +15853,24 @@ int GeneratedCodeInfo_Annotation::path_size() const {
void GeneratedCodeInfo_Annotation::clear_path() {
path_.Clear();
}
- ::google::protobuf::int32 GeneratedCodeInfo_Annotation::path(int index) const {
+::google::protobuf::int32 GeneratedCodeInfo_Annotation::path(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.path)
return path_.Get(index);
}
- void GeneratedCodeInfo_Annotation::set_path(int index, ::google::protobuf::int32 value) {
+void GeneratedCodeInfo_Annotation::set_path(int index, ::google::protobuf::int32 value) {
path_.Set(index, value);
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.path)
}
- void GeneratedCodeInfo_Annotation::add_path(::google::protobuf::int32 value) {
+void GeneratedCodeInfo_Annotation::add_path(::google::protobuf::int32 value) {
path_.Add(value);
// @@protoc_insertion_point(field_add:google.protobuf.GeneratedCodeInfo.Annotation.path)
}
- const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
+const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
GeneratedCodeInfo_Annotation::path() const {
// @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.Annotation.path)
return path_;
}
- ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
+::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
GeneratedCodeInfo_Annotation::mutable_path() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.Annotation.path)
return &path_;
@@ -15548,37 +15890,37 @@ void GeneratedCodeInfo_Annotation::clear_source_file() {
source_file_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_source_file();
}
- const ::std::string& GeneratedCodeInfo_Annotation::source_file() const {
+const ::std::string& GeneratedCodeInfo_Annotation::source_file() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
return source_file_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void GeneratedCodeInfo_Annotation::set_source_file(const ::std::string& value) {
+void GeneratedCodeInfo_Annotation::set_source_file(const ::std::string& value) {
set_has_source_file();
source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
- void GeneratedCodeInfo_Annotation::set_source_file(const char* value) {
+void GeneratedCodeInfo_Annotation::set_source_file(const char* value) {
set_has_source_file();
source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
- void GeneratedCodeInfo_Annotation::set_source_file(const char* value, size_t size) {
+void GeneratedCodeInfo_Annotation::set_source_file(const char* value, size_t size) {
set_has_source_file();
source_file_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
}
- ::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() {
+::std::string* GeneratedCodeInfo_Annotation::mutable_source_file() {
set_has_source_file();
// @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
return source_file_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* GeneratedCodeInfo_Annotation::release_source_file() {
+::std::string* GeneratedCodeInfo_Annotation::release_source_file() {
// @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file)
clear_has_source_file();
return source_file_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) {
+void GeneratedCodeInfo_Annotation::set_allocated_source_file(::std::string* source_file) {
if (source_file != NULL) {
set_has_source_file();
} else {
@@ -15602,11 +15944,11 @@ void GeneratedCodeInfo_Annotation::clear_begin() {
begin_ = 0;
clear_has_begin();
}
- ::google::protobuf::int32 GeneratedCodeInfo_Annotation::begin() const {
+::google::protobuf::int32 GeneratedCodeInfo_Annotation::begin() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.begin)
return begin_;
}
- void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 value) {
+void GeneratedCodeInfo_Annotation::set_begin(::google::protobuf::int32 value) {
set_has_begin();
begin_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.begin)
@@ -15626,16 +15968,19 @@ void GeneratedCodeInfo_Annotation::clear_end() {
end_ = 0;
clear_has_end();
}
- ::google::protobuf::int32 GeneratedCodeInfo_Annotation::end() const {
+::google::protobuf::int32 GeneratedCodeInfo_Annotation::end() const {
// @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.end)
return end_;
}
- void GeneratedCodeInfo_Annotation::set_end(::google::protobuf::int32 value) {
+void GeneratedCodeInfo_Annotation::set_end(::google::protobuf::int32 value) {
set_has_end();
end_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.end)
}
+inline const GeneratedCodeInfo_Annotation* GeneratedCodeInfo_Annotation::internal_default_instance() {
+ return &GeneratedCodeInfo_Annotation_default_instance_.get();
+}
// -------------------------------------------------------------------
// GeneratedCodeInfo
@@ -15670,6 +16015,9 @@ GeneratedCodeInfo::annotation() const {
return annotation_;
}
+inline const GeneratedCodeInfo* GeneratedCodeInfo::internal_default_instance() {
+ return &GeneratedCodeInfo_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h
index 5a9e12bc..257dd0f7 100644
--- a/src/google/protobuf/descriptor.pb.h
+++ b/src/google/protobuf/descriptor.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -35,6 +35,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
@@ -204,6 +205,8 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
static const ::google::protobuf::Descriptor* descriptor();
static const FileDescriptorSet& default_instance();
+ static const FileDescriptorSet* internal_default_instance();
+
void Swap(FileDescriptorSet* other);
// implements Message ----------------------------------------------
@@ -218,7 +221,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -234,6 +237,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FileDescriptorSet* other);
+ void UnsafeMergeFrom(const FileDescriptorSet& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -265,16 +269,18 @@ class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static FileDescriptorSet* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorSet> FileDescriptorSet_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileDescriptorProto) */ {
@@ -300,6 +306,8 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
static const ::google::protobuf::Descriptor* descriptor();
static const FileDescriptorProto& default_instance();
+ static const FileDescriptorProto* internal_default_instance();
+
void Swap(FileDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -314,7 +322,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -330,6 +338,7 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FileDescriptorProto* other);
+ void UnsafeMergeFrom(const FileDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -501,10 +510,8 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
inline void clear_has_syntax();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
- ::google::protobuf::internal::ArenaStringPtr name_;
- ::google::protobuf::internal::ArenaStringPtr package_;
::google::protobuf::RepeatedPtrField< ::std::string> dependency_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > public_dependency_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > weak_dependency_;
@@ -512,16 +519,20 @@ class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Messag
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto > service_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
+ ::google::protobuf::internal::ArenaStringPtr package_;
+ ::google::protobuf::internal::ArenaStringPtr syntax_;
::google::protobuf::FileOptions* options_;
::google::protobuf::SourceCodeInfo* source_code_info_;
- ::google::protobuf::internal::ArenaStringPtr syntax_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static FileDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FileDescriptorProto> FileDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ExtensionRange) */ {
@@ -547,6 +558,8 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
static const ::google::protobuf::Descriptor* descriptor();
static const DescriptorProto_ExtensionRange& default_instance();
+ static const DescriptorProto_ExtensionRange* internal_default_instance();
+
void Swap(DescriptorProto_ExtensionRange* other);
// implements Message ----------------------------------------------
@@ -561,7 +574,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -577,6 +590,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(DescriptorProto_ExtensionRange* other);
+ void UnsafeMergeFrom(const DescriptorProto_ExtensionRange& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -614,17 +628,19 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::proto
inline void clear_has_end();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static DescriptorProto_ExtensionRange* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ExtensionRange> DescriptorProto_ExtensionRange_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto.ReservedRange) */ {
@@ -650,6 +666,8 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
static const ::google::protobuf::Descriptor* descriptor();
static const DescriptorProto_ReservedRange& default_instance();
+ static const DescriptorProto_ReservedRange* internal_default_instance();
+
void Swap(DescriptorProto_ReservedRange* other);
// implements Message ----------------------------------------------
@@ -664,7 +682,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -680,6 +698,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(DescriptorProto_ReservedRange* other);
+ void UnsafeMergeFrom(const DescriptorProto_ReservedRange& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -717,17 +736,19 @@ class LIBPROTOBUF_EXPORT DescriptorProto_ReservedRange : public ::google::protob
inline void clear_has_end();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::int32 start_;
::google::protobuf::int32 end_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static DescriptorProto_ReservedRange* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto_ReservedRange> DescriptorProto_ReservedRange_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DescriptorProto) */ {
@@ -753,6 +774,8 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
static const ::google::protobuf::Descriptor* descriptor();
static const DescriptorProto& default_instance();
+ static const DescriptorProto* internal_default_instance();
+
void Swap(DescriptorProto* other);
// implements Message ----------------------------------------------
@@ -767,7 +790,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -783,6 +806,7 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(DescriptorProto* other);
+ void UnsafeMergeFrom(const DescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -930,25 +954,27 @@ class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message /*
inline void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
- ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange > extension_range_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::OneofDescriptorProto > oneof_decl_;
- ::google::protobuf::MessageOptions* options_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ReservedRange > reserved_range_;
::google::protobuf::RepeatedPtrField< ::std::string> reserved_name_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ ::google::protobuf::internal::ArenaStringPtr name_;
+ ::google::protobuf::MessageOptions* options_;
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static DescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<DescriptorProto> DescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldDescriptorProto) */ {
@@ -974,6 +1000,8 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
static const ::google::protobuf::Descriptor* descriptor();
static const FieldDescriptorProto& default_instance();
+ static const FieldDescriptorProto* internal_default_instance();
+
void Swap(FieldDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -988,7 +1016,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1004,6 +1032,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FieldDescriptorProto* other);
+ void UnsafeMergeFrom(const FieldDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -1226,25 +1255,27 @@ class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Messa
inline void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
- ::google::protobuf::int32 number_;
- int label_;
::google::protobuf::internal::ArenaStringPtr type_name_;
::google::protobuf::internal::ArenaStringPtr extendee_;
- int type_;
- ::google::protobuf::int32 oneof_index_;
::google::protobuf::internal::ArenaStringPtr default_value_;
::google::protobuf::internal::ArenaStringPtr json_name_;
::google::protobuf::FieldOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ ::google::protobuf::int32 number_;
+ ::google::protobuf::int32 oneof_index_;
+ int label_;
+ int type_;
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static FieldDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FieldDescriptorProto> FieldDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofDescriptorProto) */ {
@@ -1270,6 +1301,8 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
static const ::google::protobuf::Descriptor* descriptor();
static const OneofDescriptorProto& default_instance();
+ static const OneofDescriptorProto* internal_default_instance();
+
void Swap(OneofDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -1284,7 +1317,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1300,6 +1333,7 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(OneofDescriptorProto* other);
+ void UnsafeMergeFrom(const OneofDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -1344,17 +1378,19 @@ class LIBPROTOBUF_EXPORT OneofDescriptorProto : public ::google::protobuf::Messa
inline void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::OneofOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static OneofDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<OneofDescriptorProto> OneofDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumDescriptorProto) */ {
@@ -1380,6 +1416,8 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
static const ::google::protobuf::Descriptor* descriptor();
static const EnumDescriptorProto& default_instance();
+ static const EnumDescriptorProto* internal_default_instance();
+
void Swap(EnumDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -1394,7 +1432,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1410,6 +1448,7 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(EnumDescriptorProto* other);
+ void UnsafeMergeFrom(const EnumDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -1466,18 +1505,20 @@ class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Messag
inline void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
- ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto > value_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static EnumDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<EnumDescriptorProto> EnumDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueDescriptorProto) */ {
@@ -1503,6 +1544,8 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
static const ::google::protobuf::Descriptor* descriptor();
static const EnumValueDescriptorProto& default_instance();
+ static const EnumValueDescriptorProto* internal_default_instance();
+
void Swap(EnumValueDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -1517,7 +1560,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1533,6 +1576,7 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(EnumValueDescriptorProto* other);
+ void UnsafeMergeFrom(const EnumValueDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -1586,18 +1630,20 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::M
inline void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::EnumValueOptions* options_;
::google::protobuf::int32 number_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static EnumValueDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<EnumValueDescriptorProto> EnumValueDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceDescriptorProto) */ {
@@ -1623,6 +1669,8 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
static const ::google::protobuf::Descriptor* descriptor();
static const ServiceDescriptorProto& default_instance();
+ static const ServiceDescriptorProto* internal_default_instance();
+
void Swap(ServiceDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -1637,7 +1685,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1653,6 +1701,7 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(ServiceDescriptorProto* other);
+ void UnsafeMergeFrom(const ServiceDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -1709,18 +1758,20 @@ class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Mes
inline void clear_has_options();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
- ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::ServiceOptions* options_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static ServiceDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<ServiceDescriptorProto> ServiceDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodDescriptorProto) */ {
@@ -1746,6 +1797,8 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
static const ::google::protobuf::Descriptor* descriptor();
static const MethodDescriptorProto& default_instance();
+ static const MethodDescriptorProto* internal_default_instance();
+
void Swap(MethodDescriptorProto* other);
// implements Message ----------------------------------------------
@@ -1760,7 +1813,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1776,6 +1829,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(MethodDescriptorProto* other);
+ void UnsafeMergeFrom(const MethodDescriptorProto& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -1866,7 +1920,7 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
inline void clear_has_server_streaming();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr input_type_;
@@ -1874,13 +1928,15 @@ class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Mess
::google::protobuf::MethodOptions* options_;
bool client_streaming_;
bool server_streaming_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static MethodDescriptorProto* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<MethodDescriptorProto> MethodDescriptorProto_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FileOptions) */ {
@@ -1906,6 +1962,8 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const FileOptions& default_instance();
+ static const FileOptions* internal_default_instance();
+
void Swap(FileOptions* other);
// implements Message ----------------------------------------------
@@ -1920,7 +1978,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -1936,6 +1994,7 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FileOptions* other);
+ void UnsafeMergeFrom(const FileOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2010,12 +2069,12 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
bool java_multiple_files() const;
void set_java_multiple_files(bool value);
- // optional bool java_generate_equals_and_hash = 20 [default = false];
- bool has_java_generate_equals_and_hash() const;
- void clear_java_generate_equals_and_hash();
- static const int kJavaGenerateEqualsAndHashFieldNumber = 20;
- bool java_generate_equals_and_hash() const;
- void set_java_generate_equals_and_hash(bool value);
+ // optional bool java_generate_equals_and_hash = 20 [deprecated = true];
+ GOOGLE_PROTOBUF_DEPRECATED_ATTR bool has_java_generate_equals_and_hash() const;
+ GOOGLE_PROTOBUF_DEPRECATED_ATTR void clear_java_generate_equals_and_hash();
+ GOOGLE_PROTOBUF_DEPRECATED_ATTR static const int kJavaGenerateEqualsAndHashFieldNumber = 20;
+ GOOGLE_PROTOBUF_DEPRECATED_ATTR bool java_generate_equals_and_hash() const;
+ GOOGLE_PROTOBUF_DEPRECATED_ATTR void set_java_generate_equals_and_hash(bool value);
// optional bool java_string_check_utf8 = 27 [default = false];
bool has_java_string_check_utf8() const;
@@ -2149,30 +2208,32 @@ class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
::google::protobuf::internal::ArenaStringPtr java_package_;
::google::protobuf::internal::ArenaStringPtr java_outer_classname_;
+ ::google::protobuf::internal::ArenaStringPtr go_package_;
+ ::google::protobuf::internal::ArenaStringPtr objc_class_prefix_;
+ ::google::protobuf::internal::ArenaStringPtr csharp_namespace_;
bool java_multiple_files_;
bool java_generate_equals_and_hash_;
bool java_string_check_utf8_;
bool cc_generic_services_;
- int optimize_for_;
- ::google::protobuf::internal::ArenaStringPtr go_package_;
- ::google::protobuf::internal::ArenaStringPtr objc_class_prefix_;
- ::google::protobuf::internal::ArenaStringPtr csharp_namespace_;
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool java_generic_services_;
bool py_generic_services_;
bool deprecated_;
bool cc_enable_arenas_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ int optimize_for_;
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static FileOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FileOptions> FileOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MessageOptions) */ {
@@ -2198,6 +2259,8 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
static const ::google::protobuf::Descriptor* descriptor();
static const MessageOptions& default_instance();
+ static const MessageOptions* internal_default_instance();
+
void Swap(MessageOptions* other);
// implements Message ----------------------------------------------
@@ -2212,7 +2275,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -2228,6 +2291,7 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(MessageOptions* other);
+ void UnsafeMergeFrom(const MessageOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2298,20 +2362,22 @@ class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message /*
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _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 void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static MessageOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<MessageOptions> MessageOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldOptions) */ {
@@ -2337,6 +2403,8 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
static const ::google::protobuf::Descriptor* descriptor();
static const FieldOptions& default_instance();
+ static const FieldOptions* internal_default_instance();
+
void Swap(FieldOptions* other);
// implements Message ----------------------------------------------
@@ -2351,7 +2419,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -2367,6 +2435,7 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FieldOptions* other);
+ void UnsafeMergeFrom(const FieldOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2511,22 +2580,24 @@ class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message /* @@
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
int ctype_;
int jstype_;
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool packed_;
bool lazy_;
bool deprecated_;
bool weak_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static FieldOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FieldOptions> FieldOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.OneofOptions) */ {
@@ -2552,6 +2623,8 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
static const ::google::protobuf::Descriptor* descriptor();
static const OneofOptions& default_instance();
+ static const OneofOptions* internal_default_instance();
+
void Swap(OneofOptions* other);
// implements Message ----------------------------------------------
@@ -2566,7 +2639,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -2582,6 +2655,7 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(OneofOptions* other);
+ void UnsafeMergeFrom(const OneofOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2616,16 +2690,18 @@ class LIBPROTOBUF_EXPORT OneofOptions : public ::google::protobuf::Message /* @@
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static OneofOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<OneofOptions> OneofOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumOptions) */ {
@@ -2651,6 +2727,8 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const EnumOptions& default_instance();
+ static const EnumOptions* internal_default_instance();
+
void Swap(EnumOptions* other);
// implements Message ----------------------------------------------
@@ -2665,7 +2743,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -2681,6 +2759,7 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(EnumOptions* other);
+ void UnsafeMergeFrom(const EnumOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2733,18 +2812,20 @@ class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message /* @@p
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool allow_alias_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static EnumOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<EnumOptions> EnumOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValueOptions) */ {
@@ -2770,6 +2851,8 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
static const ::google::protobuf::Descriptor* descriptor();
static const EnumValueOptions& default_instance();
+ static const EnumValueOptions* internal_default_instance();
+
void Swap(EnumValueOptions* other);
// implements Message ----------------------------------------------
@@ -2784,7 +2867,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -2800,6 +2883,7 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(EnumValueOptions* other);
+ void UnsafeMergeFrom(const EnumValueOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2843,17 +2927,19 @@ class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message /
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static EnumValueOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<EnumValueOptions> EnumValueOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ServiceOptions) */ {
@@ -2879,6 +2965,8 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
static const ::google::protobuf::Descriptor* descriptor();
static const ServiceOptions& default_instance();
+ static const ServiceOptions* internal_default_instance();
+
void Swap(ServiceOptions* other);
// implements Message ----------------------------------------------
@@ -2893,7 +2981,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -2909,6 +2997,7 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(ServiceOptions* other);
+ void UnsafeMergeFrom(const ServiceOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -2952,17 +3041,19 @@ class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message /*
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static ServiceOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<ServiceOptions> ServiceOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.MethodOptions) */ {
@@ -2988,6 +3079,8 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
static const ::google::protobuf::Descriptor* descriptor();
static const MethodOptions& default_instance();
+ static const MethodOptions* internal_default_instance();
+
void Swap(MethodOptions* other);
// implements Message ----------------------------------------------
@@ -3002,7 +3095,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3018,6 +3111,7 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(MethodOptions* other);
+ void UnsafeMergeFrom(const MethodOptions& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3061,17 +3155,19 @@ class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message /* @
::google::protobuf::internal::ExtensionSet _extensions_;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_;
bool deprecated_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static MethodOptions* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<MethodOptions> MethodOptions_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption.NamePart) */ {
@@ -3097,6 +3193,8 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
static const ::google::protobuf::Descriptor* descriptor();
static const UninterpretedOption_NamePart& default_instance();
+ static const UninterpretedOption_NamePart* internal_default_instance();
+
void Swap(UninterpretedOption_NamePart* other);
// implements Message ----------------------------------------------
@@ -3111,7 +3209,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3127,6 +3225,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(UninterpretedOption_NamePart* other);
+ void UnsafeMergeFrom(const UninterpretedOption_NamePart& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3168,21 +3267,23 @@ class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobu
inline void set_has_is_extension();
inline void clear_has_is_extension();
- // helper for ByteSize()
- int RequiredFieldsByteSizeFallback() const;
+ // helper for ByteSizeLong()
+ size_t RequiredFieldsByteSizeFallback() const;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::internal::ArenaStringPtr name_part_;
bool is_extension_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static UninterpretedOption_NamePart* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption_NamePart> UninterpretedOption_NamePart_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UninterpretedOption) */ {
@@ -3208,6 +3309,8 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
static const ::google::protobuf::Descriptor* descriptor();
static const UninterpretedOption& default_instance();
+ static const UninterpretedOption* internal_default_instance();
+
void Swap(UninterpretedOption* other);
// implements Message ----------------------------------------------
@@ -3222,7 +3325,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3238,6 +3341,7 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(UninterpretedOption* other);
+ void UnsafeMergeFrom(const UninterpretedOption& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3340,22 +3444,24 @@ class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Messag
inline void clear_has_aggregate_value();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_;
::google::protobuf::internal::ArenaStringPtr identifier_value_;
+ ::google::protobuf::internal::ArenaStringPtr string_value_;
+ ::google::protobuf::internal::ArenaStringPtr aggregate_value_;
::google::protobuf::uint64 positive_int_value_;
::google::protobuf::int64 negative_int_value_;
double double_value_;
- ::google::protobuf::internal::ArenaStringPtr string_value_;
- ::google::protobuf::internal::ArenaStringPtr aggregate_value_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static UninterpretedOption* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<UninterpretedOption> UninterpretedOption_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo.Location) */ {
@@ -3381,6 +3487,8 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
static const ::google::protobuf::Descriptor* descriptor();
static const SourceCodeInfo_Location& default_instance();
+ static const SourceCodeInfo_Location* internal_default_instance();
+
void Swap(SourceCodeInfo_Location* other);
// implements Message ----------------------------------------------
@@ -3395,7 +3503,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3411,6 +3519,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(SourceCodeInfo_Location* other);
+ void UnsafeMergeFrom(const SourceCodeInfo_Location& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3498,22 +3607,24 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo_Location : public ::google::protobuf::Me
inline void clear_has_trailing_comments();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > path_;
mutable int _path_cached_byte_size_;
::google::protobuf::RepeatedField< ::google::protobuf::int32 > span_;
mutable int _span_cached_byte_size_;
+ ::google::protobuf::RepeatedPtrField< ::std::string> leading_detached_comments_;
::google::protobuf::internal::ArenaStringPtr leading_comments_;
::google::protobuf::internal::ArenaStringPtr trailing_comments_;
- ::google::protobuf::RepeatedPtrField< ::std::string> leading_detached_comments_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static SourceCodeInfo_Location* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo_Location> SourceCodeInfo_Location_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceCodeInfo) */ {
@@ -3539,6 +3650,8 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
static const ::google::protobuf::Descriptor* descriptor();
static const SourceCodeInfo& default_instance();
+ static const SourceCodeInfo* internal_default_instance();
+
void Swap(SourceCodeInfo* other);
// implements Message ----------------------------------------------
@@ -3553,7 +3666,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3569,6 +3682,7 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(SourceCodeInfo* other);
+ void UnsafeMergeFrom(const SourceCodeInfo& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3602,16 +3716,18 @@ class LIBPROTOBUF_EXPORT SourceCodeInfo : public ::google::protobuf::Message /*
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::SourceCodeInfo_Location > location_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static SourceCodeInfo* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<SourceCodeInfo> SourceCodeInfo_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo.Annotation) */ {
@@ -3637,6 +3753,8 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
static const ::google::protobuf::Descriptor* descriptor();
static const GeneratedCodeInfo_Annotation& default_instance();
+ static const GeneratedCodeInfo_Annotation* internal_default_instance();
+
void Swap(GeneratedCodeInfo_Annotation* other);
// implements Message ----------------------------------------------
@@ -3651,7 +3769,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3667,6 +3785,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(GeneratedCodeInfo_Annotation* other);
+ void UnsafeMergeFrom(const GeneratedCodeInfo_Annotation& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3730,20 +3849,22 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo_Annotation : public ::google::protobu
inline void clear_has_end();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _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 void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static GeneratedCodeInfo_Annotation* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo_Annotation> GeneratedCodeInfo_Annotation_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.GeneratedCodeInfo) */ {
@@ -3769,6 +3890,8 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
static const ::google::protobuf::Descriptor* descriptor();
static const GeneratedCodeInfo& default_instance();
+ static const GeneratedCodeInfo* internal_default_instance();
+
void Swap(GeneratedCodeInfo* other);
// implements Message ----------------------------------------------
@@ -3783,7 +3906,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -3799,6 +3922,7 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(GeneratedCodeInfo* other);
+ void UnsafeMergeFrom(const GeneratedCodeInfo& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -3832,16 +3956,18 @@ class LIBPROTOBUF_EXPORT GeneratedCodeInfo : public ::google::protobuf::Message
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- ::google::protobuf::uint32 _has_bits_[1];
+ ::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::GeneratedCodeInfo_Annotation > annotation_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fdescriptor_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto();
void InitAsDefaultInstance();
- static GeneratedCodeInfo* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<GeneratedCodeInfo> GeneratedCodeInfo_default_instance_;
+
// ===================================================================
@@ -3880,6 +4006,9 @@ FileDescriptorSet::file() const {
return file_;
}
+inline const FileDescriptorSet* FileDescriptorSet::internal_default_instance() {
+ return &FileDescriptorSet_default_instance_.get();
+}
// -------------------------------------------------------------------
// FileDescriptorProto
@@ -4243,7 +4372,8 @@ inline void FileDescriptorProto::clear_options() {
}
inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::FileOptions::internal_default_instance();
}
inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() {
set_has_options();
@@ -4287,7 +4417,8 @@ inline void FileDescriptorProto::clear_source_code_info() {
}
inline const ::google::protobuf::SourceCodeInfo& FileDescriptorProto::source_code_info() const {
// @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.source_code_info)
- return source_code_info_ != NULL ? *source_code_info_ : *default_instance_->source_code_info_;
+ return source_code_info_ != NULL ? *source_code_info_
+ : *::google::protobuf::SourceCodeInfo::internal_default_instance();
}
inline ::google::protobuf::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() {
set_has_source_code_info();
@@ -4369,6 +4500,9 @@ inline void FileDescriptorProto::set_allocated_syntax(::std::string* syntax) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax)
}
+inline const FileDescriptorProto* FileDescriptorProto::internal_default_instance() {
+ return &FileDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// DescriptorProto_ExtensionRange
@@ -4421,6 +4555,9 @@ inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 va
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ExtensionRange.end)
}
+inline const DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::internal_default_instance() {
+ return &DescriptorProto_ExtensionRange_default_instance_.get();
+}
// -------------------------------------------------------------------
// DescriptorProto_ReservedRange
@@ -4473,6 +4610,9 @@ inline void DescriptorProto_ReservedRange::set_end(::google::protobuf::int32 val
// @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.ReservedRange.end)
}
+inline const DescriptorProto_ReservedRange* DescriptorProto_ReservedRange::internal_default_instance() {
+ return &DescriptorProto_ReservedRange_default_instance_.get();
+}
// -------------------------------------------------------------------
// DescriptorProto
@@ -4727,7 +4867,8 @@ inline void DescriptorProto::clear_options() {
}
inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::MessageOptions::internal_default_instance();
}
inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() {
set_has_options();
@@ -4840,6 +4981,9 @@ DescriptorProto::mutable_reserved_name() {
return &reserved_name_;
}
+inline const DescriptorProto* DescriptorProto::internal_default_instance() {
+ return &DescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// FieldDescriptorProto
@@ -5228,7 +5372,8 @@ inline void FieldDescriptorProto::clear_options() {
}
inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::FieldOptions::internal_default_instance();
}
inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() {
set_has_options();
@@ -5256,6 +5401,9 @@ inline void FieldDescriptorProto::set_allocated_options(::google::protobuf::Fiel
// @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.options)
}
+inline const FieldDescriptorProto* FieldDescriptorProto::internal_default_instance() {
+ return &FieldDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// OneofDescriptorProto
@@ -5330,7 +5478,8 @@ inline void OneofDescriptorProto::clear_options() {
}
inline const ::google::protobuf::OneofOptions& OneofDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::OneofOptions::internal_default_instance();
}
inline ::google::protobuf::OneofOptions* OneofDescriptorProto::mutable_options() {
set_has_options();
@@ -5358,6 +5507,9 @@ inline void OneofDescriptorProto::set_allocated_options(::google::protobuf::Oneo
// @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options)
}
+inline const OneofDescriptorProto* OneofDescriptorProto::internal_default_instance() {
+ return &OneofDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// EnumDescriptorProto
@@ -5462,7 +5614,8 @@ inline void EnumDescriptorProto::clear_options() {
}
inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::EnumOptions::internal_default_instance();
}
inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() {
set_has_options();
@@ -5490,6 +5643,9 @@ inline void EnumDescriptorProto::set_allocated_options(::google::protobuf::EnumO
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options)
}
+inline const EnumDescriptorProto* EnumDescriptorProto::internal_default_instance() {
+ return &EnumDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// EnumValueDescriptorProto
@@ -5588,7 +5744,8 @@ inline void EnumValueDescriptorProto::clear_options() {
}
inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::EnumValueOptions::internal_default_instance();
}
inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() {
set_has_options();
@@ -5616,6 +5773,9 @@ inline void EnumValueDescriptorProto::set_allocated_options(::google::protobuf::
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options)
}
+inline const EnumValueDescriptorProto* EnumValueDescriptorProto::internal_default_instance() {
+ return &EnumValueDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// ServiceDescriptorProto
@@ -5720,7 +5880,8 @@ inline void ServiceDescriptorProto::clear_options() {
}
inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::ServiceOptions::internal_default_instance();
}
inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() {
set_has_options();
@@ -5748,6 +5909,9 @@ inline void ServiceDescriptorProto::set_allocated_options(::google::protobuf::Se
// @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options)
}
+inline const ServiceDescriptorProto* ServiceDescriptorProto::internal_default_instance() {
+ return &ServiceDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// MethodDescriptorProto
@@ -5930,7 +6094,8 @@ inline void MethodDescriptorProto::clear_options() {
}
inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const {
// @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.options)
- return options_ != NULL ? *options_ : *default_instance_->options_;
+ return options_ != NULL ? *options_
+ : *::google::protobuf::MethodOptions::internal_default_instance();
}
inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() {
set_has_options();
@@ -6006,6 +6171,9 @@ inline void MethodDescriptorProto::set_server_streaming(bool value) {
// @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.server_streaming)
}
+inline const MethodDescriptorProto* MethodDescriptorProto::internal_default_instance() {
+ return &MethodDescriptorProto_default_instance_.get();
+}
// -------------------------------------------------------------------
// FileOptions
@@ -6142,7 +6310,7 @@ inline void FileOptions::set_java_multiple_files(bool value) {
// @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_multiple_files)
}
-// optional bool java_generate_equals_and_hash = 20 [default = false];
+// optional bool java_generate_equals_and_hash = 20 [deprecated = true];
inline bool FileOptions::has_java_generate_equals_and_hash() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
@@ -6527,6 +6695,9 @@ FileOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const FileOptions* FileOptions::internal_default_instance() {
+ return &FileOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// MessageOptions
@@ -6657,6 +6828,9 @@ MessageOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const MessageOptions* MessageOptions::internal_default_instance() {
+ return &MessageOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// FieldOptions
@@ -6837,6 +7011,9 @@ FieldOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const FieldOptions* FieldOptions::internal_default_instance() {
+ return &FieldOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// OneofOptions
@@ -6871,6 +7048,9 @@ OneofOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const OneofOptions* OneofOptions::internal_default_instance() {
+ return &OneofOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// EnumOptions
@@ -6953,6 +7133,9 @@ EnumOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const EnumOptions* EnumOptions::internal_default_instance() {
+ return &EnumOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// EnumValueOptions
@@ -7011,6 +7194,9 @@ EnumValueOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const EnumValueOptions* EnumValueOptions::internal_default_instance() {
+ return &EnumValueOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// ServiceOptions
@@ -7069,6 +7255,9 @@ ServiceOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const ServiceOptions* ServiceOptions::internal_default_instance() {
+ return &ServiceOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// MethodOptions
@@ -7127,6 +7316,9 @@ MethodOptions::uninterpreted_option() const {
return uninterpreted_option_;
}
+inline const MethodOptions* MethodOptions::internal_default_instance() {
+ return &MethodOptions_default_instance_.get();
+}
// -------------------------------------------------------------------
// UninterpretedOption_NamePart
@@ -7209,6 +7401,9 @@ inline void UninterpretedOption_NamePart::set_is_extension(bool value) {
// @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.is_extension)
}
+inline const UninterpretedOption_NamePart* UninterpretedOption_NamePart::internal_default_instance() {
+ return &UninterpretedOption_NamePart_default_instance_.get();
+}
// -------------------------------------------------------------------
// UninterpretedOption
@@ -7477,6 +7672,9 @@ inline void UninterpretedOption::set_allocated_aggregate_value(::std::string* ag
// @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value)
}
+inline const UninterpretedOption* UninterpretedOption::internal_default_instance() {
+ return &UninterpretedOption_default_instance_.get();
+}
// -------------------------------------------------------------------
// SourceCodeInfo_Location
@@ -7704,6 +7902,9 @@ SourceCodeInfo_Location::mutable_leading_detached_comments() {
return &leading_detached_comments_;
}
+inline const SourceCodeInfo_Location* SourceCodeInfo_Location::internal_default_instance() {
+ return &SourceCodeInfo_Location_default_instance_.get();
+}
// -------------------------------------------------------------------
// SourceCodeInfo
@@ -7738,6 +7939,9 @@ SourceCodeInfo::location() const {
return location_;
}
+inline const SourceCodeInfo* SourceCodeInfo::internal_default_instance() {
+ return &SourceCodeInfo_default_instance_.get();
+}
// -------------------------------------------------------------------
// GeneratedCodeInfo_Annotation
@@ -7874,6 +8078,9 @@ inline void GeneratedCodeInfo_Annotation::set_end(::google::protobuf::int32 valu
// @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.end)
}
+inline const GeneratedCodeInfo_Annotation* GeneratedCodeInfo_Annotation::internal_default_instance() {
+ return &GeneratedCodeInfo_Annotation_default_instance_.get();
+}
// -------------------------------------------------------------------
// GeneratedCodeInfo
@@ -7908,6 +8115,9 @@ GeneratedCodeInfo::annotation() const {
return annotation_;
}
+inline const GeneratedCodeInfo* GeneratedCodeInfo::internal_default_instance() {
+ return &GeneratedCodeInfo_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto
index 28410d4a..558ae23e 100644
--- a/src/google/protobuf/descriptor.proto
+++ b/src/google/protobuf/descriptor.proto
@@ -45,7 +45,6 @@ option java_package = "com.google.protobuf";
option java_outer_classname = "DescriptorProtos";
option csharp_namespace = "Google.Protobuf.Reflection";
option objc_class_prefix = "GPB";
-option java_generate_equals_and_hash = true;
// descriptor.proto must be optimized for speed because reflection-based
// algorithms don't work during bootstrapping.
@@ -306,19 +305,8 @@ message FileOptions {
// top-level extensions defined in the file.
optional bool java_multiple_files = 10 [default=false];
- // If set true, then the Java code generator will generate equals() and
- // hashCode() methods for all messages defined in the .proto file.
- // This increases generated code size, potentially substantially for large
- // protos, which may harm a memory-constrained application.
- // - In the full runtime this is a speed optimization, as the
- // AbstractMessage base class includes reflection-based implementations of
- // these methods.
- // - In the lite runtime, setting this option changes the semantics of
- // equals() and hashCode() to more closely match those of the full runtime;
- // the generated methods compute their results based on field values rather
- // than object identity. (Implementations should not assume that hashcodes
- // will be consistent across runtimes or versions of the protocol compiler.)
- optional bool java_generate_equals_and_hash = 20 [default=false];
+ // This option does nothing.
+ optional bool java_generate_equals_and_hash = 20 [deprecated=true];
// If set true, then the Java2 code generator will generate code that
// throws an exception whenever an attempt is made to assign a non-UTF-8
@@ -448,6 +436,8 @@ message MessageOptions {
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
+
+ reserved 8; // javalite_serializable
}
message FieldOptions {
@@ -471,7 +461,6 @@ message FieldOptions {
// false will avoid using packed encoding.
optional bool packed = 2;
-
// The jstype option determines the JavaScript type used for values of the
// field. The option is permitted only for 64 bit integral and fixed types
// (int64, uint64, sint64, fixed64, sfixed64). By default these types are
@@ -512,7 +501,7 @@ message FieldOptions {
//
//
// Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outher message
+ // a lazy sub-message. That is, calling IsInitialized() on the outer message
// may return true even if the inner message has missing required fields.
// This is necessary because otherwise the inner message would have to be
// parsed in order to perform the check, defeating the purpose of lazy
@@ -538,6 +527,8 @@ message FieldOptions {
// Clients can define custom options in extensions of this message. See above.
extensions 1000 to max;
+
+ reserved 4; // removed jtype
}
message OneofOptions {
diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc
index 4183138f..f6b3f1c5 100644
--- a/src/google/protobuf/descriptor_unittest.cc
+++ b/src/google/protobuf/descriptor_unittest.cc
@@ -773,9 +773,9 @@ TEST_F(DescriptorTest, FieldFullName) {
TEST_F(DescriptorTest, FieldJsonName) {
EXPECT_EQ("fieldName1", message4_->field(0)->json_name());
EXPECT_EQ("fieldName2", message4_->field(1)->json_name());
- EXPECT_EQ("fieldName3", message4_->field(2)->json_name());
- EXPECT_EQ("fieldName4", message4_->field(3)->json_name());
- EXPECT_EQ("fIELDNAME5", message4_->field(4)->json_name());
+ EXPECT_EQ("FieldName3", message4_->field(2)->json_name());
+ EXPECT_EQ("FieldName4", message4_->field(3)->json_name());
+ EXPECT_EQ("FIELDNAME5", message4_->field(4)->json_name());
EXPECT_EQ("@type", message4_->field(5)->json_name());
DescriptorProto proto;
@@ -793,10 +793,20 @@ TEST_F(DescriptorTest, FieldJsonName) {
ASSERT_EQ(6, proto.field_size());
EXPECT_EQ("fieldName1", proto.field(0).json_name());
EXPECT_EQ("fieldName2", proto.field(1).json_name());
- EXPECT_EQ("fieldName3", proto.field(2).json_name());
- EXPECT_EQ("fieldName4", proto.field(3).json_name());
- EXPECT_EQ("fIELDNAME5", proto.field(4).json_name());
+ EXPECT_EQ("FieldName3", proto.field(2).json_name());
+ EXPECT_EQ("FieldName4", proto.field(3).json_name());
+ EXPECT_EQ("FIELDNAME5", proto.field(4).json_name());
EXPECT_EQ("@type", proto.field(5).json_name());
+
+ // Test generated descriptor.
+ const Descriptor* generated = protobuf_unittest::TestJsonName::descriptor();
+ ASSERT_EQ(6, generated->field_count());
+ EXPECT_EQ("fieldName1", generated->field(0)->json_name());
+ EXPECT_EQ("fieldName2", generated->field(1)->json_name());
+ EXPECT_EQ("FieldName3", generated->field(2)->json_name());
+ EXPECT_EQ("FieldName4", generated->field(3)->json_name());
+ EXPECT_EQ("FIELDNAME5", generated->field(4)->json_name());
+ EXPECT_EQ("@type", generated->field(5)->json_name());
}
TEST_F(DescriptorTest, FieldFile) {
@@ -5553,6 +5563,69 @@ TEST_F(ValidationErrorTest, MapEntryConflictsWithEnum) {
"with an existing enum type.\n");
}
+TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) {
+ BuildFileWithErrors(
+ "syntax: 'proto3'"
+ "name: 'foo.proto' "
+ "enum_type {"
+ " name: 'FooEnum' "
+ " value { name: 'FOO_ENUM_BAZ' number: 0 }"
+ " value { name: 'BAZ' number: 1 }"
+ "}",
+ "foo.proto: BAZ: NAME: When enum name is stripped and label is "
+ "PascalCased (Baz), this value label conflicts with FOO_ENUM_BAZ. This "
+ "will make the proto fail to compile for some languages, such as C#.\n");
+
+ BuildFileWithErrors(
+ "syntax: 'proto3'"
+ "name: 'foo.proto' "
+ "enum_type {"
+ " name: 'FooEnum' "
+ " value { name: 'FOOENUM_BAZ' number: 0 }"
+ " value { name: 'BAZ' number: 1 }"
+ "}",
+ "foo.proto: BAZ: NAME: When enum name is stripped and label is "
+ "PascalCased (Baz), this value label conflicts with FOOENUM_BAZ. This "
+ "will make the proto fail to compile for some languages, such as C#.\n");
+
+ BuildFileWithErrors(
+ "syntax: 'proto3'"
+ "name: 'foo.proto' "
+ "enum_type {"
+ " name: 'FooEnum' "
+ " value { name: 'FOO_ENUM_BAR_BAZ' number: 0 }"
+ " value { name: 'BAR__BAZ' number: 1 }"
+ "}",
+ "foo.proto: BAR__BAZ: NAME: When enum name is stripped and label is "
+ "PascalCased (BarBaz), this value label conflicts with "
+ "FOO_ENUM_BAR_BAZ. This "
+ "will make the proto fail to compile for some languages, such as C#.\n");
+
+ BuildFileWithErrors(
+ "syntax: 'proto3'"
+ "name: 'foo.proto' "
+ "enum_type {"
+ " name: 'FooEnum' "
+ " value { name: 'FOO_ENUM__BAR_BAZ' number: 0 }"
+ " value { name: 'BAR_BAZ' number: 1 }"
+ "}",
+ "foo.proto: BAR_BAZ: NAME: When enum name is stripped and label is "
+ "PascalCased (BarBaz), this value label conflicts with "
+ "FOO_ENUM__BAR_BAZ. This "
+ "will make the proto fail to compile for some languages, such as C#.\n");
+
+ // This isn't an error because the underscore will cause the PascalCase to
+ // differ by case (BarBaz vs. Barbaz).
+ BuildFile(
+ "syntax: 'proto3'"
+ "name: 'foo.proto' "
+ "enum_type {"
+ " name: 'FooEnum' "
+ " value { name: 'BAR_BAZ' number: 0 }"
+ " value { name: 'BARBAZ' number: 1 }"
+ "}");
+}
+
TEST_F(ValidationErrorTest, MapEntryConflictsWithOneof) {
FileDescriptorProto file_proto;
FillValidMapEntry(&file_proto);
diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc
index 94ece18e..f7cc647f 100644
--- a/src/google/protobuf/duration.pb.cc
+++ b/src/google/protobuf/duration.pb.cc
@@ -44,20 +44,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fduration_2eproto() {
Duration_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Duration_descriptor_,
- Duration::default_instance_,
+ Duration::internal_default_instance(),
Duration_offsets_,
-1,
-1,
-1,
sizeof(Duration),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Duration, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Duration, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Duration, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fduration_2eproto);
}
@@ -66,37 +65,49 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Duration_descriptor_, &Duration::default_instance());
+ Duration_descriptor_, Duration::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto() {
- delete Duration::default_instance_;
+ Duration_default_instance_.Shutdown();
delete Duration_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ Duration_default_instance_.DefaultConstruct();
+ Duration_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\036google/protobuf/duration.proto\022\017google"
".protobuf\"*\n\010Duration\022\017\n\007seconds\030\001 \001(\003\022\r"
"\n\005nanos\030\002 \001(\005B|\n\023com.google.protobufB\rDu"
"rationProtoP\001Z*github.com/golang/protobu"
- "f/ptypes/duration\240\001\001\242\002\003GPB\252\002\036Google.Prot"
+ "f/ptypes/duration\370\001\001\242\002\003GPB\252\002\036Google.Prot"
"obuf.WellKnownTypesb\006proto3", 227);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/duration.proto", &protobuf_RegisterTypes);
- Duration::default_instance_ = new Duration();
- Duration::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fduration_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fduration_2eproto() {
@@ -104,6 +115,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fduration_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2fduration_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -113,27 +134,36 @@ const int Duration::kNanosFieldNumber;
Duration::Duration()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Duration)
}
+Duration::Duration(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Duration)
+}
void Duration::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Duration::Duration(const Duration& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Duration)
}
void Duration::SharedCtor() {
- _is_default_instance_ = false;
+ ::memset(&seconds_, 0, reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
_cached_size_ = 0;
- seconds_ = GOOGLE_LONGLONG(0);
- nanos_ = 0;
}
Duration::~Duration() {
@@ -142,10 +172,19 @@ Duration::~Duration() {
}
void Duration::SharedDtor() {
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
}
+
}
+void Duration::ArenaDtor(void* object) {
+ Duration* _this = reinterpret_cast< Duration* >(object);
+ (void)_this;
+}
+void Duration::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Duration::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -157,18 +196,14 @@ const ::google::protobuf::Descriptor* Duration::descriptor() {
}
const Duration& Duration::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
+ return *internal_default_instance();
}
-Duration* Duration::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Duration> Duration_default_instance_;
Duration* Duration::New(::google::protobuf::Arena* arena) const {
- Duration* n = new Duration;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Duration>(arena);
}
void Duration::Clear() {
@@ -185,7 +220,7 @@ void Duration::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -209,10 +244,10 @@ bool Duration::MergePartialFromCodedStream(
// optional int64 seconds = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &seconds_)));
-
} else {
goto handle_unusual;
}
@@ -224,10 +259,10 @@ bool Duration::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_nanos:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &nanos_)));
-
} else {
goto handle_unusual;
}
@@ -274,6 +309,7 @@ void Duration::SerializeWithCachedSizes(
::google::protobuf::uint8* Duration::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Duration)
// optional int64 seconds = 1;
if (this->seconds() != 0) {
@@ -289,9 +325,9 @@ void Duration::SerializeWithCachedSizes(
return target;
}
-int Duration::ByteSize() const {
+size_t Duration::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Duration)
- int total_size = 0;
+ size_t total_size = 0;
// optional int64 seconds = 1;
if (this->seconds() != 0) {
@@ -307,18 +343,17 @@ int Duration::ByteSize() const {
this->nanos());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Duration::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Duration)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Duration* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Duration* source =
::google::protobuf::internal::DynamicCastToGenerated<const Duration>(
&from);
if (source == NULL) {
@@ -326,15 +361,21 @@ void Duration::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Duration)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Duration::MergeFrom(const Duration& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Duration)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Duration::UnsafeMergeFrom(const Duration& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.seconds() != 0) {
set_seconds(from.seconds());
}
@@ -354,7 +395,7 @@ void Duration::CopyFrom(const Duration& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Duration)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Duration::IsInitialized() const {
@@ -364,6 +405,18 @@ bool Duration::IsInitialized() const {
void Duration::Swap(Duration* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Duration temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Duration::UnsafeArenaSwap(Duration* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Duration::InternalSwap(Duration* other) {
@@ -388,11 +441,11 @@ void Duration::InternalSwap(Duration* other) {
void Duration::clear_seconds() {
seconds_ = GOOGLE_LONGLONG(0);
}
- ::google::protobuf::int64 Duration::seconds() const {
+::google::protobuf::int64 Duration::seconds() const {
// @@protoc_insertion_point(field_get:google.protobuf.Duration.seconds)
return seconds_;
}
- void Duration::set_seconds(::google::protobuf::int64 value) {
+void Duration::set_seconds(::google::protobuf::int64 value) {
seconds_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Duration.seconds)
@@ -402,16 +455,19 @@ void Duration::clear_seconds() {
void Duration::clear_nanos() {
nanos_ = 0;
}
- ::google::protobuf::int32 Duration::nanos() const {
+::google::protobuf::int32 Duration::nanos() const {
// @@protoc_insertion_point(field_get:google.protobuf.Duration.nanos)
return nanos_;
}
- void Duration::set_nanos(::google::protobuf::int32 value) {
+void Duration::set_nanos(::google::protobuf::int32 value) {
nanos_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Duration.nanos)
}
+inline const Duration* Duration::internal_default_instance() {
+ return &Duration_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h
index ad479639..3ed1a6d3 100644
--- a/src/google/protobuf/duration.pb.h
+++ b/src/google/protobuf/duration.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -34,6 +34,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fduration_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto();
@@ -53,9 +54,16 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Duration& default_instance();
+ static const Duration* internal_default_instance();
+
+ void UnsafeArenaSwap(Duration* other);
void Swap(Duration* other);
// implements Message ----------------------------------------------
@@ -70,7 +78,7 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -86,6 +94,12 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Duration* other);
+ void UnsafeMergeFrom(const Duration& from);
+ protected:
+ explicit Duration(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -117,17 +131,21 @@ class LIBPROTOBUF_EXPORT Duration : public ::google::protobuf::Message /* @@prot
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fduration_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fduration_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fduration_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fduration_2eproto();
void InitAsDefaultInstance();
- static Duration* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Duration> Duration_default_instance_;
+
// ===================================================================
@@ -164,6 +182,9 @@ inline void Duration::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(field_set:google.protobuf.Duration.nanos)
}
+inline const Duration* Duration::internal_default_instance() {
+ return &Duration_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/duration.proto b/src/google/protobuf/duration.proto
index 96c1796d..7f461f40 100644
--- a/src/google/protobuf/duration.proto
+++ b/src/google/protobuf/duration.proto
@@ -33,11 +33,11 @@ syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/duration";
option java_package = "com.google.protobuf";
option java_outer_classname = "DurationProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// A Duration represents a signed, fixed-length span of time represented
@@ -81,6 +81,12 @@ option objc_class_prefix = "GPB";
// end.nanos -= 1000000000;
// }
//
+// Example 3: Compute Duration from datetime.timedelta in Python.
+//
+// td = datetime.timedelta(days=3, minutes=10)
+// duration = Duration()
+// duration.FromTimedelta(td)
+//
//
message Duration {
diff --git a/src/google/protobuf/dynamic_message.cc b/src/google/protobuf/dynamic_message.cc
index 5d914bf6..f51bc9d6 100644
--- a/src/google/protobuf/dynamic_message.cc
+++ b/src/google/protobuf/dynamic_message.cc
@@ -223,7 +223,6 @@ class DynamicMessage : public Message {
int oneof_case_offset;
int unknown_fields_offset;
int extensions_offset;
- int is_default_instance_offset;
// Not owned by the TypeInfo.
DynamicMessageFactory* factory; // The factory that created this object.
@@ -332,11 +331,6 @@ void DynamicMessage::SharedCtor() {
uint32(0);
}
- if (type_info_->is_default_instance_offset != -1) {
- *reinterpret_cast<bool*>(
- OffsetToPointer(type_info_->is_default_instance_offset)) = false;
- }
-
new(OffsetToPointer(type_info_->unknown_fields_offset)) UnknownFieldSet;
if (type_info_->extensions_offset != -1) {
@@ -556,14 +550,6 @@ void DynamicMessage::CrossLinkPrototypes() {
factory->GetPrototypeNoLock(field->message_type());
}
}
-
- // Set as the default instance -- this affects field-presence semantics for
- // proto3.
- if (type_info_->is_default_instance_offset != -1) {
- void* is_default_instance_ptr =
- OffsetToPointer(type_info_->is_default_instance_offset);
- *reinterpret_cast<bool*>(is_default_instance_ptr) = true;
- }
}
Message* DynamicMessage::New() const {
@@ -683,15 +669,6 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock(
size = AlignOffset(size);
}
- // The is_default_instance member, if any.
- if (type->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
- type_info->is_default_instance_offset = size;
- size += sizeof(bool);
- size = AlignOffset(size);
- } else {
- type_info->is_default_instance_offset = -1;
- }
-
// The oneof_case, if any. It is an array of uint32s.
if (type->oneof_decl_count() > 0) {
type_info->oneof_case_offset = size;
@@ -769,35 +746,18 @@ const Message* DynamicMessageFactory::GetPrototypeNoLock(
ConstructDefaultOneofInstance(type_info->type,
type_info->offsets.get(),
type_info->default_oneof_instance);
- type_info->reflection.reset(
- new GeneratedMessageReflection(
- type_info->type,
- type_info->prototype,
- type_info->offsets.get(),
- type_info->has_bits_offset,
- type_info->unknown_fields_offset,
- type_info->extensions_offset,
- type_info->default_oneof_instance,
- type_info->oneof_case_offset,
- type_info->pool,
- this,
- type_info->size,
- -1 /* arena_offset */,
- type_info->is_default_instance_offset));
+ type_info->reflection.reset(new GeneratedMessageReflection(
+ type_info->type, type_info->prototype, type_info->offsets.get(),
+ type_info->has_bits_offset, type_info->unknown_fields_offset,
+ type_info->extensions_offset, type_info->default_oneof_instance,
+ type_info->oneof_case_offset, type_info->pool, this, type_info->size,
+ -1 /* arena_offset */));
} else {
- type_info->reflection.reset(
- new GeneratedMessageReflection(
- type_info->type,
- type_info->prototype,
- type_info->offsets.get(),
- type_info->has_bits_offset,
- type_info->unknown_fields_offset,
- type_info->extensions_offset,
- type_info->pool,
- this,
- type_info->size,
- -1 /* arena_offset */,
- type_info->is_default_instance_offset));
+ type_info->reflection.reset(new GeneratedMessageReflection(
+ type_info->type, type_info->prototype, type_info->offsets.get(),
+ type_info->has_bits_offset, type_info->unknown_fields_offset,
+ type_info->extensions_offset, type_info->pool, this, type_info->size,
+ -1 /* arena_offset */));
}
// Cross link prototypes.
prototype->CrossLinkPrototypes();
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc
index 83775753..f19bf2a6 100644
--- a/src/google/protobuf/empty.pb.cc
+++ b/src/google/protobuf/empty.pb.cc
@@ -42,20 +42,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fempty_2eproto() {
Empty_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Empty_descriptor_,
- Empty::default_instance_,
+ Empty::internal_default_instance(),
Empty_offsets_,
-1,
-1,
-1,
sizeof(Empty),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Empty, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Empty, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Empty, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fempty_2eproto);
}
@@ -64,36 +63,48 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Empty_descriptor_, &Empty::default_instance());
+ Empty_descriptor_, Empty::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto() {
- delete Empty::default_instance_;
+ Empty_default_instance_.Shutdown();
delete Empty_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ Empty_default_instance_.DefaultConstruct();
+ Empty_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\033google/protobuf/empty.proto\022\017google.pr"
- "otobuf\"\007\n\005EmptyBy\n\023com.google.protobufB\n"
+ "otobuf\"\007\n\005EmptyBv\n\023com.google.protobufB\n"
"EmptyProtoP\001Z\'github.com/golang/protobuf"
- "/ptypes/empty\240\001\001\370\001\001\242\002\003GPB\252\002\036Google.Proto"
- "buf.WellKnownTypesb\006proto3", 186);
+ "/ptypes/empty\370\001\001\242\002\003GPB\252\002\036Google.Protobuf"
+ ".WellKnownTypesb\006proto3", 183);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/empty.proto", &protobuf_RegisterTypes);
- Empty::default_instance_ = new Empty();
- Empty::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fempty_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fempty_2eproto() {
@@ -101,6 +112,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fempty_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2fempty_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -108,32 +129,33 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fempty_2eproto {
Empty::Empty()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Empty)
}
-
Empty::Empty(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Empty)
}
void Empty::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Empty::Empty(const Empty& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Empty)
}
void Empty::SharedCtor() {
- _is_default_instance_ = false;
_cached_size_ = 0;
}
@@ -143,12 +165,11 @@ Empty::~Empty() {
}
void Empty::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void Empty::ArenaDtor(void* object) {
@@ -168,11 +189,11 @@ const ::google::protobuf::Descriptor* Empty::descriptor() {
}
const Empty& Empty::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
+ return *internal_default_instance();
}
-Empty* Empty::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Empty> Empty_default_instance_;
Empty* Empty::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<Empty>(arena);
@@ -216,27 +237,27 @@ void Empty::SerializeWithCachedSizes(
::google::protobuf::uint8* Empty::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Empty)
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Empty)
return target;
}
-int Empty::ByteSize() const {
+size_t Empty::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Empty)
- int total_size = 0;
+ size_t total_size = 0;
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Empty::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Empty)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Empty* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Empty* source =
::google::protobuf::internal::DynamicCastToGenerated<const Empty>(
&from);
if (source == NULL) {
@@ -244,17 +265,23 @@ void Empty::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Empty)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Empty::MergeFrom(const Empty& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Empty)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
}
+void Empty::UnsafeMergeFrom(const Empty& from) {
+ GOOGLE_DCHECK(&from != this);
+}
+
void Empty::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Empty)
if (&from == this) return;
@@ -266,7 +293,7 @@ void Empty::CopyFrom(const Empty& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Empty)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Empty::IsInitialized() const {
@@ -280,7 +307,7 @@ void Empty::Swap(Empty* other) {
InternalSwap(other);
} else {
Empty temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -306,6 +333,9 @@ void Empty::InternalSwap(Empty* other) {
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Empty
+inline const Empty* Empty::internal_default_instance() {
+ return &Empty_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h
index 8e78733b..29309366 100644
--- a/src/google/protobuf/empty.pb.h
+++ b/src/google/protobuf/empty.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -34,6 +34,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fempty_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto();
@@ -60,6 +61,8 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
static const ::google::protobuf::Descriptor* descriptor();
static const Empty& default_instance();
+ static const Empty* internal_default_instance();
+
void UnsafeArenaSwap(Empty* other);
void Swap(Empty* other);
@@ -75,7 +78,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -91,6 +94,7 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Empty* other);
+ void UnsafeMergeFrom(const Empty& from);
protected:
explicit Empty(::google::protobuf::Arena* arena);
private:
@@ -118,15 +122,16 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fempty_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fempty_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fempty_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fempty_2eproto();
void InitAsDefaultInstance();
- static Empty* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Empty> Empty_default_instance_;
+
// ===================================================================
@@ -135,6 +140,9 @@ class LIBPROTOBUF_EXPORT Empty : public ::google::protobuf::Message /* @@protoc_
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// Empty
+inline const Empty* Empty::internal_default_instance() {
+ return &Empty_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/empty.proto b/src/google/protobuf/empty.proto
index 37f4cd10..03cacd23 100644
--- a/src/google/protobuf/empty.proto
+++ b/src/google/protobuf/empty.proto
@@ -37,7 +37,6 @@ option go_package = "github.com/golang/protobuf/ptypes/empty";
option java_package = "com.google.protobuf";
option java_outer_classname = "EmptyProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
option cc_enable_arenas = true;
diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc
index 7d20a0f8..ad164e3e 100644
--- a/src/google/protobuf/extension_set.cc
+++ b/src/google/protobuf/extension_set.cc
@@ -1354,8 +1354,8 @@ void ExtensionSet::SerializeWithCachedSizes(
}
}
-int ExtensionSet::ByteSize() const {
- int total_size = 0;
+size_t ExtensionSet::ByteSize() const {
+ size_t total_size = 0;
for (ExtensionMap::const_iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
@@ -1536,8 +1536,8 @@ void ExtensionSet::Extension::SerializeFieldWithCachedSizes(
}
}
-int ExtensionSet::Extension::ByteSize(int number) const {
- int result = 0;
+size_t ExtensionSet::Extension::ByteSize(int number) const {
+ size_t result = 0;
if (is_repeated) {
if (is_packed) {
@@ -1563,7 +1563,7 @@ int ExtensionSet::Extension::ByteSize(int number) const {
#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \
case WireFormatLite::TYPE_##UPPERCASE: \
result += WireFormatLite::k##CAMELCASE##Size * \
- repeated_##LOWERCASE##_value->size(); \
+ FromIntSize(repeated_##LOWERCASE##_value->size()); \
break
HANDLE_TYPE( FIXED32, Fixed32, uint32);
HANDLE_TYPE( FIXED64, Fixed64, uint64);
@@ -1582,7 +1582,7 @@ int ExtensionSet::Extension::ByteSize(int number) const {
break;
}
- cached_size = result;
+ cached_size = ToCachedSize(result);
if (result > 0) {
result += io::CodedOutputStream::VarintSize32(result);
result += io::CodedOutputStream::VarintSize32(
@@ -1590,12 +1590,13 @@ int ExtensionSet::Extension::ByteSize(int number) const {
WireFormatLite::WIRETYPE_LENGTH_DELIMITED));
}
} else {
- int tag_size = WireFormatLite::TagSize(number, real_type(type));
+ size_t tag_size = WireFormatLite::TagSize(number, real_type(type));
switch (real_type(type)) {
#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \
case WireFormatLite::TYPE_##UPPERCASE: \
- result += tag_size * repeated_##LOWERCASE##_value->size(); \
+ result += tag_size * \
+ FromIntSize(repeated_##LOWERCASE##_value->size()); \
for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \
result += WireFormatLite::CAMELCASE##Size( \
repeated_##LOWERCASE##_value->Get(i)); \
@@ -1619,7 +1620,7 @@ int ExtensionSet::Extension::ByteSize(int number) const {
#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \
case WireFormatLite::TYPE_##UPPERCASE: \
result += (tag_size + WireFormatLite::k##CAMELCASE##Size) * \
- repeated_##LOWERCASE##_value->size(); \
+ FromIntSize(repeated_##LOWERCASE##_value->size()); \
break
HANDLE_TYPE( FIXED32, Fixed32, uint32);
HANDLE_TYPE( FIXED64, Fixed64, uint64);
@@ -1652,7 +1653,7 @@ int ExtensionSet::Extension::ByteSize(int number) const {
#undef HANDLE_TYPE
case WireFormatLite::TYPE_MESSAGE: {
if (is_lazy) {
- int size = lazymessage_value->ByteSize();
+ size_t size = lazymessage_value->ByteSize();
result += io::CodedOutputStream::VarintSize32(size) + size;
} else {
result += WireFormatLite::MessageSize(*message_value);
diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h
index 3e1d1ef5..f5aa8de9 100644
--- a/src/google/protobuf/extension_set.h
+++ b/src/google/protobuf/extension_set.h
@@ -423,10 +423,10 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
uint8* SerializeMessageSetWithCachedSizesToArray(uint8* target) const;
// Returns the total serialized size of all the extensions.
- int ByteSize() const;
+ size_t ByteSize() const;
// Like ByteSize() but uses MessageSet format.
- int MessageSetByteSize() const;
+ size_t MessageSetByteSize() const;
// Returns (an estimate of) the total number of bytes used for storing the
// extensions in memory, excluding sizeof(*this). If the ExtensionSet is
@@ -551,8 +551,8 @@ class LIBPROTOBUF_EXPORT ExtensionSet {
int number,
bool deterministic,
uint8* target) const;
- int ByteSize(int number) const;
- int MessageSetItemByteSize(int number) const;
+ size_t ByteSize(int number) const;
+ size_t MessageSetItemByteSize(int number) const;
void Clear();
int GetSize() const;
void Free();
diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc
index b26a246c..1bbc8fef 100644
--- a/src/google/protobuf/extension_set_heavy.cc
+++ b/src/google/protobuf/extension_set_heavy.cc
@@ -749,7 +749,7 @@ void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes(
output->WriteTag(WireFormatLite::kMessageSetItemEndTag);
}
-int ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
+size_t ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) {
// Not a valid MessageSet extension, but compute the byte size for it the
// normal way.
@@ -758,13 +758,13 @@ int ExtensionSet::Extension::MessageSetItemByteSize(int number) const {
if (is_cleared) return 0;
- int our_size = WireFormatLite::kMessageSetItemTagsSize;
+ size_t our_size = WireFormatLite::kMessageSetItemTagsSize;
// type_id
our_size += io::CodedOutputStream::VarintSize32(number);
// message
- int message_size = 0;
+ size_t message_size = 0;
if (is_lazy) {
message_size = lazymessage_value->ByteSize();
} else {
@@ -785,8 +785,8 @@ void ExtensionSet::SerializeMessageSetWithCachedSizes(
}
}
-int ExtensionSet::MessageSetByteSize() const {
- int total_size = 0;
+size_t ExtensionSet::MessageSetByteSize() const {
+ size_t total_size = 0;
for (ExtensionMap::const_iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc
index 688afedb..a70a2ff6 100644
--- a/src/google/protobuf/extension_set_unittest.cc
+++ b/src/google/protobuf/extension_set_unittest.cc
@@ -796,7 +796,7 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) {
} \
int expected_size = sizeof(cpptype) * (16 - \
kMinRepeatedFieldAllocationSize) + empty_repeated_field_size; \
- EXPECT_EQ(expected_size, message.SpaceUsed()) << #type; \
+ EXPECT_LE(expected_size, message.SpaceUsed()) << #type; \
} while (0)
TEST_REPEATED_EXTENSIONS_SPACE_USED(int32 , int32 , 101);
diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc
index ed05fe57..5d80d297 100644
--- a/src/google/protobuf/field_mask.pb.cc
+++ b/src/google/protobuf/field_mask.pb.cc
@@ -43,20 +43,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2ffield_5fmask_2eproto() {
FieldMask_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FieldMask_descriptor_,
- FieldMask::default_instance_,
+ FieldMask::internal_default_instance(),
FieldMask_offsets_,
-1,
-1,
-1,
sizeof(FieldMask),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldMask, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldMask, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldMask, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2ffield_5fmask_2eproto);
}
@@ -65,36 +64,49 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FieldMask_descriptor_, &FieldMask::default_instance());
+ FieldMask_descriptor_, FieldMask::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto() {
- delete FieldMask::default_instance_;
+ FieldMask_default_instance_.Shutdown();
delete FieldMask_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ ::google::protobuf::internal::GetEmptyString();
+ FieldMask_default_instance_.DefaultConstruct();
+ FieldMask_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n google/protobuf/field_mask.proto\022\017goog"
"le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB"
- "Q\n\023com.google.protobufB\016FieldMaskProtoP\001"
- "\240\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTyp"
- "esb\006proto3", 170);
+ "N\n\023com.google.protobufB\016FieldMaskProtoP\001"
+ "\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypesb"
+ "\006proto3", 167);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/field_mask.proto", &protobuf_RegisterTypes);
- FieldMask::default_instance_ = new FieldMask();
- FieldMask::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2ffield_5fmask_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2ffield_5fmask_2eproto() {
@@ -102,6 +114,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2ffield_5fmask_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2ffield_5fmask_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -110,25 +132,23 @@ const int FieldMask::kPathsFieldNumber;
FieldMask::FieldMask()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FieldMask)
}
void FieldMask::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
FieldMask::FieldMask(const FieldMask& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask)
}
void FieldMask::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
_cached_size_ = 0;
}
@@ -138,8 +158,6 @@ FieldMask::~FieldMask() {
}
void FieldMask::SharedDtor() {
- if (this != default_instance_) {
- }
}
void FieldMask::SetCachedSize(int size) const {
@@ -153,11 +171,11 @@ const ::google::protobuf::Descriptor* FieldMask::descriptor() {
}
const FieldMask& FieldMask::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
+ return *internal_default_instance();
}
-FieldMask* FieldMask::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FieldMask> FieldMask_default_instance_;
FieldMask* FieldMask::New(::google::protobuf::Arena* arena) const {
FieldMask* n = new FieldMask;
@@ -240,6 +258,7 @@ void FieldMask::SerializeWithCachedSizes(
::google::protobuf::uint8* FieldMask::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FieldMask)
// repeated string paths = 1;
for (int i = 0; i < this->paths_size(); i++) {
@@ -255,29 +274,29 @@ void FieldMask::SerializeWithCachedSizes(
return target;
}
-int FieldMask::ByteSize() const {
+size_t FieldMask::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FieldMask)
- int total_size = 0;
+ size_t total_size = 0;
// repeated string paths = 1;
- total_size += 1 * this->paths_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->paths_size());
for (int i = 0; i < this->paths_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->paths(i));
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FieldMask::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FieldMask)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FieldMask* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FieldMask* source =
::google::protobuf::internal::DynamicCastToGenerated<const FieldMask>(
&from);
if (source == NULL) {
@@ -285,16 +304,22 @@ void FieldMask::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FieldMask)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FieldMask::MergeFrom(const FieldMask& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FieldMask)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
- paths_.MergeFrom(from.paths_);
+}
+
+void FieldMask::UnsafeMergeFrom(const FieldMask& from) {
+ GOOGLE_DCHECK(&from != this);
+ paths_.UnsafeMergeFrom(from.paths_);
}
void FieldMask::CopyFrom(const ::google::protobuf::Message& from) {
@@ -308,7 +333,7 @@ void FieldMask::CopyFrom(const FieldMask& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FieldMask)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FieldMask::IsInitialized() const {
@@ -344,54 +369,57 @@ int FieldMask::paths_size() const {
void FieldMask::clear_paths() {
paths_.Clear();
}
- const ::std::string& FieldMask::paths(int index) const {
+const ::std::string& FieldMask::paths(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.FieldMask.paths)
return paths_.Get(index);
}
- ::std::string* FieldMask::mutable_paths(int index) {
+::std::string* FieldMask::mutable_paths(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.FieldMask.paths)
return paths_.Mutable(index);
}
- void FieldMask::set_paths(int index, const ::std::string& value) {
+void FieldMask::set_paths(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths)
paths_.Mutable(index)->assign(value);
}
- void FieldMask::set_paths(int index, const char* value) {
+void FieldMask::set_paths(int index, const char* value) {
paths_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.FieldMask.paths)
}
- void FieldMask::set_paths(int index, const char* value, size_t size) {
+void FieldMask::set_paths(int index, const char* value, size_t size) {
paths_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldMask.paths)
}
- ::std::string* FieldMask::add_paths() {
+::std::string* FieldMask::add_paths() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.FieldMask.paths)
return paths_.Add();
}
- void FieldMask::add_paths(const ::std::string& value) {
+void FieldMask::add_paths(const ::std::string& value) {
paths_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths)
}
- void FieldMask::add_paths(const char* value) {
+void FieldMask::add_paths(const char* value) {
paths_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.FieldMask.paths)
}
- void FieldMask::add_paths(const char* value, size_t size) {
+void FieldMask::add_paths(const char* value, size_t size) {
paths_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.FieldMask.paths)
}
- const ::google::protobuf::RepeatedPtrField< ::std::string>&
+const ::google::protobuf::RepeatedPtrField< ::std::string>&
FieldMask::paths() const {
// @@protoc_insertion_point(field_list:google.protobuf.FieldMask.paths)
return paths_;
}
- ::google::protobuf::RepeatedPtrField< ::std::string>*
+::google::protobuf::RepeatedPtrField< ::std::string>*
FieldMask::mutable_paths() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldMask.paths)
return &paths_;
}
+inline const FieldMask* FieldMask::internal_default_instance() {
+ return &FieldMask_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h
index 7a19c4aa..17cb6bbf 100644
--- a/src/google/protobuf/field_mask.pb.h
+++ b/src/google/protobuf/field_mask.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -34,6 +34,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto();
@@ -56,6 +57,8 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const FieldMask& default_instance();
+ static const FieldMask* internal_default_instance();
+
void Swap(FieldMask* other);
// implements Message ----------------------------------------------
@@ -70,7 +73,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -86,6 +89,7 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FieldMask* other);
+ void UnsafeMergeFrom(const FieldMask& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -121,16 +125,17 @@ class LIBPROTOBUF_EXPORT FieldMask : public ::google::protobuf::Message /* @@pro
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
::google::protobuf::RepeatedPtrField< ::std::string> paths_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ffield_5fmask_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ffield_5fmask_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ffield_5fmask_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ffield_5fmask_2eproto();
void InitAsDefaultInstance();
- static FieldMask* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FieldMask> FieldMask_default_instance_;
+
// ===================================================================
@@ -194,6 +199,9 @@ FieldMask::mutable_paths() {
return &paths_;
}
+inline const FieldMask* FieldMask::internal_default_instance() {
+ return &FieldMask_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/field_mask.proto b/src/google/protobuf/field_mask.proto
index c51de09a..b6d32a79 100644
--- a/src/google/protobuf/field_mask.proto
+++ b/src/google/protobuf/field_mask.proto
@@ -37,7 +37,6 @@ option java_package = "com.google.protobuf";
option java_outer_classname = "FieldMaskProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";
-option java_generate_equals_and_hash = true;
// `FieldMask` represents a set of symbolic field paths, for example:
//
@@ -82,7 +81,7 @@ option java_generate_equals_and_hash = true;
// }
//
// A repeated field is not allowed except at the last position of a
-// field mask.
+// paths string.
//
// If a FieldMask object is not present in a get operation, the
// operation applies to all fields (as if a FieldMask of all fields
@@ -109,8 +108,8 @@ option java_generate_equals_and_hash = true;
//
// If a repeated field is specified for an update operation, the existing
// repeated values in the target resource will be overwritten by the new values.
-// Note that a repeated field is only allowed in the last position of a field
-// mask.
+// Note that a repeated field is only allowed in the last position of a `paths`
+// string.
//
// If a sub-message is specified in the last position of the field mask for an
// update operation, then the existing sub-message in the target resource is
diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc
index d1f7b5ca..6f418433 100644
--- a/src/google/protobuf/generated_message_reflection.cc
+++ b/src/google/protobuf/generated_message_reflection.cc
@@ -173,62 +173,43 @@ static void ReportReflectionUsageEnumTypeError(
// ===================================================================
GeneratedMessageReflection::GeneratedMessageReflection(
- const Descriptor* descriptor,
- const Message* default_instance,
- const int offsets[],
- int has_bits_offset,
- int unknown_fields_offset,
- int extensions_offset,
- const DescriptorPool* descriptor_pool,
- MessageFactory* factory,
- int object_size,
- int arena_offset,
- int is_default_instance_offset)
- : descriptor_ (descriptor),
- default_instance_ (default_instance),
- offsets_ (offsets),
- has_bits_offset_ (has_bits_offset),
- unknown_fields_offset_(unknown_fields_offset),
- extensions_offset_(extensions_offset),
- arena_offset_ (arena_offset),
- is_default_instance_offset_(is_default_instance_offset),
- object_size_ (object_size),
- descriptor_pool_ ((descriptor_pool == NULL) ?
- DescriptorPool::generated_pool() :
- descriptor_pool),
- message_factory_ (factory) {
-}
+ const Descriptor* descriptor, const Message* default_instance,
+ const int offsets[], int has_bits_offset, int unknown_fields_offset,
+ int extensions_offset, const DescriptorPool* descriptor_pool,
+ MessageFactory* factory, int object_size, int arena_offset)
+ : descriptor_(descriptor),
+ default_instance_(default_instance),
+ offsets_(offsets),
+ has_bits_offset_(has_bits_offset),
+ unknown_fields_offset_(unknown_fields_offset),
+ extensions_offset_(extensions_offset),
+ arena_offset_(arena_offset),
+ object_size_(object_size),
+ descriptor_pool_((descriptor_pool == NULL)
+ ? DescriptorPool::generated_pool()
+ : descriptor_pool),
+ message_factory_(factory) {}
GeneratedMessageReflection::GeneratedMessageReflection(
- const Descriptor* descriptor,
- const Message* default_instance,
- const int offsets[],
- int has_bits_offset,
- int unknown_fields_offset,
- int extensions_offset,
- const void* default_oneof_instance,
- int oneof_case_offset,
- const DescriptorPool* descriptor_pool,
- MessageFactory* factory,
- int object_size,
- int arena_offset,
- int is_default_instance_offset)
- : descriptor_ (descriptor),
- default_instance_ (default_instance),
- default_oneof_instance_ (default_oneof_instance),
- offsets_ (offsets),
- has_bits_offset_ (has_bits_offset),
- oneof_case_offset_(oneof_case_offset),
- unknown_fields_offset_(unknown_fields_offset),
- extensions_offset_(extensions_offset),
- arena_offset_ (arena_offset),
- is_default_instance_offset_(is_default_instance_offset),
- object_size_ (object_size),
- descriptor_pool_ ((descriptor_pool == NULL) ?
- DescriptorPool::generated_pool() :
- descriptor_pool),
- message_factory_ (factory) {
-}
+ const Descriptor* descriptor, const Message* default_instance,
+ const int offsets[], int has_bits_offset, int unknown_fields_offset,
+ int extensions_offset, const void* default_oneof_instance,
+ int oneof_case_offset, const DescriptorPool* descriptor_pool,
+ MessageFactory* factory, int object_size, int arena_offset)
+ : descriptor_(descriptor),
+ default_instance_(default_instance),
+ default_oneof_instance_(default_oneof_instance),
+ offsets_(offsets),
+ has_bits_offset_(has_bits_offset),
+ oneof_case_offset_(oneof_case_offset),
+ unknown_fields_offset_(unknown_fields_offset),
+ extensions_offset_(extensions_offset),
+ arena_offset_(arena_offset),
+ object_size_(object_size),
+ descriptor_pool_((descriptor_pool == NULL)
+ ? DescriptorPool::generated_pool()
+ : descriptor_pool),
+ message_factory_(factory) {}
GeneratedMessageReflection::~GeneratedMessageReflection() {}
@@ -1026,6 +1007,11 @@ struct FieldNumberSorter {
return left->number() < right->number();
}
};
+
+inline bool IsIndexInHasBitSet(const uint32* has_bit_set, uint32 index) {
+ return ((has_bit_set[index / 32] >> (index % 32)) & static_cast<uint32>(1))
+ != 0;
+}
} // namespace
void GeneratedMessageReflection::ListFields(
@@ -1036,6 +1022,12 @@ void GeneratedMessageReflection::ListFields(
// Optimization: The default instance never has any fields set.
if (&message == default_instance_) return;
+ // Optimization: Avoid calling GetHasBits() and HasOneofField() many times
+ // within the field loop.
+ const uint32* const has_bits = GetHasBits(message);
+ const uint32* const oneof_case_array = reinterpret_cast<const uint32*>(
+ reinterpret_cast<const uint8*>(&message) + oneof_case_offset_);
+
output->reserve(descriptor_->field_count());
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = descriptor_->field(i);
@@ -1044,11 +1036,18 @@ void GeneratedMessageReflection::ListFields(
output->push_back(field);
}
} else {
- if (field->containing_oneof()) {
- if (HasOneofField(message, field)) {
+ const OneofDescriptor* containing_oneof = field->containing_oneof();
+ if (containing_oneof) {
+ // Equivalent to: HasOneofField(message, field)
+ if (oneof_case_array[containing_oneof->index()] == field->number()) {
output->push_back(field);
}
- } else if (HasBit(message, field)) {
+ } else if (has_bits) {
+ // Equivalent to: HasBit(message, field)
+ if (IsIndexInHasBitSet(has_bits, i)) {
+ output->push_back(field);
+ }
+ } else if (HasBit(message, field)) { // Fall back on proto3-style HasBit.
output->push_back(field);
}
}
@@ -2001,12 +2000,7 @@ GeneratedMessageReflection::MutableInternalMetadataWithArena(
inline bool
GeneratedMessageReflection::GetIsDefaultInstance(
const Message& message) const {
- if (is_default_instance_offset_ == kHasNoDefaultInstanceField) {
- return false;
- }
- const void* ptr = reinterpret_cast<const uint8*>(&message) +
- is_default_instance_offset_;
- return *reinterpret_cast<const bool*>(ptr);
+ return &message == default_instance_;
}
// Simple accessors for manipulating has_bits_.
@@ -2063,8 +2057,7 @@ inline bool GeneratedMessageReflection::HasBit(
}
}
}
- return GetHasBits(message)[field->index() / 32] &
- (1 << (field->index() % 32));
+ return IsIndexInHasBitSet(GetHasBits(message), field->index());
}
inline void GeneratedMessageReflection::SetBit(
@@ -2072,7 +2065,9 @@ inline void GeneratedMessageReflection::SetBit(
if (has_bits_offset_ == -1) {
return;
}
- MutableHasBits(message)[field->index() / 32] |= (1 << (field->index() % 32));
+ const uint32 index = static_cast<uint32>(field->index());
+ MutableHasBits(message)[index / 32] |=
+ (static_cast<uint32>(1) << (index % 32));
}
inline void GeneratedMessageReflection::ClearBit(
@@ -2080,7 +2075,9 @@ inline void GeneratedMessageReflection::ClearBit(
if (has_bits_offset_ == -1) {
return;
}
- MutableHasBits(message)[field->index() / 32] &= ~(1 << (field->index() % 32));
+ const uint32 index = static_cast<uint32>(field->index());
+ MutableHasBits(message)[index / 32] &=
+ ~(static_cast<uint32>(1) << (index % 32));
}
inline void GeneratedMessageReflection::SwapBit(
@@ -2275,19 +2272,11 @@ GeneratedMessageReflection::NewGeneratedMessageReflection(
int object_size,
int arena_offset,
int is_default_instance_offset) {
- return new GeneratedMessageReflection(descriptor,
- default_instance,
- offsets,
- has_bits_offset,
- unknown_fields_offset,
- extensions_offset,
- default_oneof_instance,
- oneof_case_offset,
- DescriptorPool::generated_pool(),
- MessageFactory::generated_factory(),
- object_size,
- arena_offset,
- is_default_instance_offset);
+ return new GeneratedMessageReflection(
+ descriptor, default_instance, offsets, has_bits_offset,
+ unknown_fields_offset, extensions_offset, default_oneof_instance,
+ oneof_case_offset, DescriptorPool::generated_pool(),
+ MessageFactory::generated_factory(), object_size, arena_offset);
}
GeneratedMessageReflection*
@@ -2301,17 +2290,11 @@ GeneratedMessageReflection::NewGeneratedMessageReflection(
int object_size,
int arena_offset,
int is_default_instance_offset) {
- return new GeneratedMessageReflection(descriptor,
- default_instance,
- offsets,
- has_bits_offset,
- unknown_fields_offset,
- extensions_offset,
- DescriptorPool::generated_pool(),
- MessageFactory::generated_factory(),
- object_size,
- arena_offset,
- is_default_instance_offset);
+ return new GeneratedMessageReflection(
+ descriptor, default_instance, offsets, has_bits_offset,
+ unknown_fields_offset, extensions_offset,
+ DescriptorPool::generated_pool(), MessageFactory::generated_factory(),
+ object_size, arena_offset);
}
} // namespace internal
diff --git a/src/google/protobuf/generated_message_reflection.h b/src/google/protobuf/generated_message_reflection.h
index 15fc802c..1413b110 100644
--- a/src/google/protobuf/generated_message_reflection.h
+++ b/src/google/protobuf/generated_message_reflection.h
@@ -132,15 +132,11 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection : public Reflection {
// by sizeof().
GeneratedMessageReflection(const Descriptor* descriptor,
const Message* default_instance,
- const int offsets[],
- int has_bits_offset,
- int unknown_fields_offset,
- int extensions_offset,
+ const int offsets[], int has_bits_offset,
+ int unknown_fields_offset, int extensions_offset,
const DescriptorPool* pool,
- MessageFactory* factory,
- int object_size,
- int arena_offset,
- int is_default_instance_offset = -1);
+ MessageFactory* factory, int object_size,
+ int arena_offset);
// Similar with the construction above. Call this construction if the
// message has oneof definition.
@@ -168,17 +164,12 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection : public Reflection {
// other parameters are the same with the construction above.
GeneratedMessageReflection(const Descriptor* descriptor,
const Message* default_instance,
- const int offsets[],
- int has_bits_offset,
- int unknown_fields_offset,
- int extensions_offset,
+ const int offsets[], int has_bits_offset,
+ int unknown_fields_offset, int extensions_offset,
const void* default_oneof_instance,
- int oneof_case_offset,
- const DescriptorPool* pool,
- MessageFactory* factory,
- int object_size,
- int arena_offset,
- int is_default_instance_offset = -1);
+ int oneof_case_offset, const DescriptorPool* pool,
+ MessageFactory* factory, int object_size,
+ int arena_offset);
~GeneratedMessageReflection();
// Shorter-to-call helpers for the above two constructions that work if the
@@ -226,11 +217,11 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection : public Reflection {
Message* ReleaseLast(Message* message, const FieldDescriptor* field) const;
void Swap(Message* message1, Message* message2) const;
void SwapFields(Message* message1, Message* message2,
- const vector<const FieldDescriptor*>& fields) const;
+ const std::vector<const FieldDescriptor*>& fields) const;
void SwapElements(Message* message, const FieldDescriptor* field,
int index1, int index2) const;
void ListFields(const Message& message,
- vector<const FieldDescriptor*>* output) const;
+ std::vector<const FieldDescriptor*>* output) const;
int32 GetInt32 (const Message& message,
const FieldDescriptor* field) const;
@@ -448,11 +439,8 @@ class LIBPROTOBUF_EXPORT GeneratedMessageReflection : public Reflection {
int unknown_fields_offset_;
int extensions_offset_;
int arena_offset_;
- int is_default_instance_offset_;
int object_size_;
- static const int kHasNoDefaultInstanceField = -1;
-
const DescriptorPool* descriptor_pool_;
MessageFactory* message_factory_;
diff --git a/src/google/protobuf/generated_message_util.cc b/src/google/protobuf/generated_message_util.cc
index 7ad6d61c..73f55927 100644
--- a/src/google/protobuf/generated_message_util.cc
+++ b/src/google/protobuf/generated_message_util.cc
@@ -48,15 +48,15 @@ double NaN() {
return std::numeric_limits<double>::quiet_NaN();
}
-const ::std::string* empty_string_;
+ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
GOOGLE_PROTOBUF_DECLARE_ONCE(empty_string_once_init_);
void DeleteEmptyString() {
- delete empty_string_;
+ GetEmptyStringAlreadyInited().~string();
}
void InitEmptyString() {
- empty_string_ = new string;
+ fixed_address_empty_string.DefaultConstruct();
OnShutdown(&DeleteEmptyString);
}
diff --git a/src/google/protobuf/generated_message_util.h b/src/google/protobuf/generated_message_util.h
index 8967726e..8dc64c49 100644
--- a/src/google/protobuf/generated_message_util.h
+++ b/src/google/protobuf/generated_message_util.h
@@ -43,6 +43,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
+#include <google/protobuf/has_bits.h>
namespace google {
@@ -70,22 +71,55 @@ namespace internal {
LIBPROTOBUF_EXPORT double Infinity();
LIBPROTOBUF_EXPORT double NaN();
+// This type is used to define a global variable, without it's constructor
+// and destructor run on start and end of the program lifetime. This circumvents
+// the initial construction order fiasco, while keeping the address of the
+// empty string a compile time constant.
+template <typename T>
+class ExplicitlyConstructed {
+ public:
+ void DefaultConstruct() {
+ new (&union_) T();
+ init_ = true;
+ }
+
+ bool IsInitialized() { return init_; }
+ void Shutdown() {
+ if (init_) {
+ init_ = false;
+ get_mutable()->~T();
+ }
+ }
+
+ const T& get() const { return reinterpret_cast<const T&>(union_); }
+ T* get_mutable() { return reinterpret_cast<T*>(&union_); }
+
+ private:
+ // Prefer c++14 aligned_storage, but for compatibility this will do.
+ union AlignedUnion {
+ char space[sizeof(T)];
+ int64 align_to_int64;
+ void* align_to_ptr;
+ } union_;
+ bool init_; // false by linker
+};
+
// TODO(jieluo): Change to template. We have tried to use template,
// but it causes net/rpc/python:rpcutil_test fail (the empty string will
// init twice). It may related to swig. Change to template after we
// found the solution.
-// Default empty string object. Don't use the pointer directly. Instead, call
+// Default empty string object. Don't use this directly. Instead, call
// GetEmptyString() to get the reference.
-LIBPROTOBUF_EXPORT extern const ::std::string* empty_string_;
+extern ExplicitlyConstructed< ::std::string> fixed_address_empty_string;
LIBPROTOBUF_EXPORT extern ProtobufOnceType empty_string_once_init_;
LIBPROTOBUF_EXPORT void InitEmptyString();
LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyStringAlreadyInited() {
- assert(empty_string_ != NULL);
- return *empty_string_;
+ return fixed_address_empty_string.get();
}
+
LIBPROTOBUF_EXPORT inline const ::std::string& GetEmptyString() {
::google::protobuf::GoogleOnceInit(&empty_string_once_init_, &InitEmptyString);
return GetEmptyStringAlreadyInited();
@@ -106,20 +140,28 @@ template <class Type> bool AllAreInitialized(const Type& t) {
return true;
}
-class ArenaString;
-
-// Read a length (varint32), followed by a string, from *input. Return a
-// pointer to a copy of the string that resides in *arena. Requires both
-// args to be non-NULL. If something goes wrong while reading the data
-// then NULL is returned (e.g., input does not start with a valid varint).
-LIBPROTOBUF_EXPORT ArenaString* ReadArenaString(
- ::google::protobuf::io::CodedInputStream* input,
- ::google::protobuf::Arena* arena);
-
// Helper function to crash on merge failure.
// Moved out of generated code to reduce binary size.
LIBPROTOBUF_EXPORT void MergeFromFail(const char* file, int line) GOOGLE_ATTRIBUTE_NORETURN;
+// We compute sizes as size_t but cache them as int. This function converts a
+// computed size to a cached size. Since we don't proceed with serialization if
+// the total size was > INT_MAX, it is not important what this function returns
+// for inputs > INT_MAX.
+inline int ToCachedSize(size_t size) {
+ return static_cast<int>(size);
+}
+
+// We mainly calculate sizes in terms of size_t, but some functions that compute
+// sizes return "int". These int sizes are expected to always be positive.
+// This function is more efficient than casting an int to size_t directly on
+// 64-bit platforms because it avoids making the compiler emit a sign extending
+// instruction, which we don't want and don't want to pay for.
+inline size_t FromIntSize(int size) {
+ // Convert to unsigned before widening so sign extension is not necessary.
+ return static_cast<unsigned int>(size);
+}
+
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/has_bits.h b/src/google/protobuf/has_bits.h
new file mode 100644
index 00000000..133bc02a
--- /dev/null
+++ b/src/google/protobuf/has_bits.h
@@ -0,0 +1,72 @@
+// 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_HAS_BITS_H__
+#define GOOGLE_PROTOBUF_HAS_BITS_H__
+
+#include <google/protobuf/stubs/common.h>
+
+namespace google {
+namespace protobuf {
+namespace internal {
+
+template<size_t doublewords>
+class HasBits {
+ public:
+ HasBits() GOOGLE_ATTRIBUTE_ALWAYS_INLINE { Clear(); }
+
+ void Clear() GOOGLE_ATTRIBUTE_ALWAYS_INLINE {
+ memset(has_bits_, 0, sizeof(has_bits_));
+ }
+
+ ::google::protobuf::uint32& operator[](int index) GOOGLE_ATTRIBUTE_ALWAYS_INLINE {
+ return has_bits_[index];
+ }
+
+ const ::google::protobuf::uint32& operator[](int index) const GOOGLE_ATTRIBUTE_ALWAYS_INLINE {
+ return has_bits_[index];
+ }
+
+ bool operator==(const HasBits<doublewords>& rhs) const {
+ return memcmp(has_bits_, rhs.has_bits_, sizeof(has_bits_)) == 0;
+ }
+
+ bool operator!=(const HasBits<doublewords>& rhs) const {
+ return !(*this == rhs);
+ }
+ private:
+ ::google::protobuf::uint32 has_bits_[doublewords];
+};
+
+} // namespace internal
+} // namespace protobuf
+
+} // namespace google
+#endif // GOOGLE_PROTOBUF_HAS_BITS_H__
diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc
index a5675e79..08394ca7 100644
--- a/src/google/protobuf/io/coded_stream.cc
+++ b/src/google/protobuf/io/coded_stream.cc
@@ -47,6 +47,7 @@
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/stl_util.h>
+#include <google/protobuf/stubs/port.h>
namespace google {
@@ -902,46 +903,18 @@ bool CodedOutputStream::Refresh() {
}
}
-int CodedOutputStream::VarintSize32Fallback(uint32 value) {
+size_t CodedOutputStream::VarintSize32Fallback(uint32 value) {
+ GOOGLE_DCHECK_NE(0, value); // This is enforced by our caller.
+
+ return 1 + Bits::Log2FloorNonZero(value) / 7;
+}
+
+size_t CodedOutputStream::VarintSize64(uint64 value) {
if (value < (1 << 7)) {
return 1;
- } else if (value < (1 << 14)) {
- return 2;
- } else if (value < (1 << 21)) {
- return 3;
- } else if (value < (1 << 28)) {
- return 4;
- } else {
- return 5;
}
-}
-int CodedOutputStream::VarintSize64(uint64 value) {
- if (value < (1ull << 35)) {
- if (value < (1ull << 7)) {
- return 1;
- } else if (value < (1ull << 14)) {
- return 2;
- } else if (value < (1ull << 21)) {
- return 3;
- } else if (value < (1ull << 28)) {
- return 4;
- } else {
- return 5;
- }
- } else {
- if (value < (1ull << 42)) {
- return 6;
- } else if (value < (1ull << 49)) {
- return 7;
- } else if (value < (1ull << 56)) {
- return 8;
- } else if (value < (1ull << 63)) {
- return 9;
- } else {
- return 10;
- }
- }
+ return 1 + Bits::Log2FloorNonZero64(value) / 7;
}
uint8* CodedOutputStream::WriteStringWithSizeToArray(const string& str,
diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h
index 316da765..1402cc17 100644
--- a/src/google/protobuf/io/coded_stream.h
+++ b/src/google/protobuf/io/coded_stream.h
@@ -784,17 +784,17 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
uint8* target);
// Returns the number of bytes needed to encode the given value as a varint.
- static int VarintSize32(uint32 value);
+ static size_t VarintSize32(uint32 value);
// Returns the number of bytes needed to encode the given value as a varint.
- static int VarintSize64(uint64 value);
+ static size_t VarintSize64(uint64 value);
// If negative, 10 bytes. Otheriwse, same as VarintSize32().
- static int VarintSize32SignExtended(int32 value);
+ static size_t VarintSize32SignExtended(int32 value);
// Compile-time equivalent of VarintSize32().
template <uint32 Value>
struct StaticVarintSize32 {
- static const int value =
+ static const size_t value =
(Value < (1 << 7))
? 1
: (Value < (1 << 14))
@@ -890,7 +890,7 @@ class LIBPROTOBUF_EXPORT CodedOutputStream {
GOOGLE_ATTRIBUTE_ALWAYS_INLINE static uint8* WriteVarint64ToArrayInline(
uint64 value, uint8* target);
- static int VarintSize32Fallback(uint32 value);
+ static size_t VarintSize32Fallback(uint32 value);
// See above. Other projects may use "friend" to allow them to call this.
static void SetDefaultSerializationDeterministic() {
@@ -1225,7 +1225,7 @@ inline uint8* CodedOutputStream::WriteTagToArray(
return WriteVarint32ToArray(value, target);
}
-inline int CodedOutputStream::VarintSize32(uint32 value) {
+inline size_t CodedOutputStream::VarintSize32(uint32 value) {
if (value < (1 << 7)) {
return 1;
} else {
@@ -1233,7 +1233,7 @@ inline int CodedOutputStream::VarintSize32(uint32 value) {
}
}
-inline int CodedOutputStream::VarintSize32SignExtended(int32 value) {
+inline size_t CodedOutputStream::VarintSize32SignExtended(int32 value) {
if (value < 0) {
return 10; // TODO(kenton): Make this a symbolic constant.
} else {
diff --git a/src/google/protobuf/io/coded_stream_unittest.cc b/src/google/protobuf/io/coded_stream_unittest.cc
index a8108e45..9f1ebc3f 100644
--- a/src/google/protobuf/io/coded_stream_unittest.cc
+++ b/src/google/protobuf/io/coded_stream_unittest.cc
@@ -58,6 +58,7 @@
#define ULL(x) GOOGLE_ULONGLONG(x)
namespace google {
+
namespace protobuf {
namespace io {
namespace {
diff --git a/src/google/protobuf/io/zero_copy_stream_impl.h b/src/google/protobuf/io/zero_copy_stream_impl.h
index 0746fa6a..3365790e 100644
--- a/src/google/protobuf/io/zero_copy_stream_impl.h
+++ b/src/google/protobuf/io/zero_copy_stream_impl.h
@@ -218,7 +218,7 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
// If a block_size is given, it specifies the number of bytes that
// should be read and returned with each call to Next(). Otherwise,
// a reasonable default is used.
- explicit IstreamInputStream(istream* stream, int block_size = -1);
+ explicit IstreamInputStream(std::istream* stream, int block_size = -1);
~IstreamInputStream();
// implements ZeroCopyInputStream ----------------------------------
@@ -230,7 +230,7 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
private:
class LIBPROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream {
public:
- CopyingIstreamInputStream(istream* input);
+ CopyingIstreamInputStream(std::istream* input);
~CopyingIstreamInputStream();
// implements CopyingInputStream ---------------------------------
@@ -239,7 +239,7 @@ class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream {
private:
// The stream.
- istream* input_;
+ std::istream* input_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingIstreamInputStream);
};
@@ -262,7 +262,7 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
// If a block_size is given, it specifies the size of the buffers
// that should be returned by Next(). Otherwise, a reasonable default
// is used.
- explicit OstreamOutputStream(ostream* stream, int block_size = -1);
+ explicit OstreamOutputStream(std::ostream* stream, int block_size = -1);
~OstreamOutputStream();
// implements ZeroCopyOutputStream ---------------------------------
@@ -273,7 +273,7 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
private:
class LIBPROTOBUF_EXPORT CopyingOstreamOutputStream : public CopyingOutputStream {
public:
- CopyingOstreamOutputStream(ostream* output);
+ CopyingOstreamOutputStream(std::ostream* output);
~CopyingOstreamOutputStream();
// implements CopyingOutputStream --------------------------------
@@ -281,7 +281,7 @@ class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream {
private:
// The stream.
- ostream* output_;
+ std::ostream* output_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOstreamOutputStream);
};
diff --git a/src/google/protobuf/map.h b/src/google/protobuf/map.h
index 1b9aa703..2d295510 100644
--- a/src/google/protobuf/map.h
+++ b/src/google/protobuf/map.h
@@ -28,6 +28,12 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// This file defines the map container and its helpers to support protobuf maps.
+//
+// The Map and MapIterator types are provided by this header file.
+// Please avoid using other types defined here, unless they are public
+// types within Map or MapIterator, such as Map::value_type.
+
#ifndef GOOGLE_PROTOBUF_MAP_H__
#define GOOGLE_PROTOBUF_MAP_H__
@@ -50,9 +56,6 @@
namespace google {
namespace protobuf {
-// The Map and MapIterator types are provided by this header file.
-// Please avoid using other types defined here, unless they are public
-// types within Map or MapIterator, such as Map::value_type.
template <typename Key, typename T>
class Map;
@@ -562,7 +565,7 @@ class Map {
void Init() {
if (old_style_)
deprecated_elements_ = Arena::Create<DeprecatedInnerMap>(
- arena_, 0, hasher(), equal_to<Key>(),
+ arena_, 0, hasher(), std::equal_to<Key>(),
MapAllocator<std::pair<const Key, MapPair<Key, T>*> >(arena_));
else
elements_ =
@@ -593,7 +596,7 @@ class Map {
// If arena is not given, malloc needs to be called which doesn't
// construct element object.
if (arena_ == NULL) {
- return reinterpret_cast<pointer>(malloc(n * sizeof(value_type)));
+ return static_cast<pointer>(::operator new(n * sizeof(value_type)));
} else {
return reinterpret_cast<pointer>(
Arena::CreateArray<uint8>(arena_, n * sizeof(value_type)));
@@ -602,7 +605,11 @@ class Map {
void deallocate(pointer p, size_type n) {
if (arena_ == NULL) {
- free(p);
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ ::operator delete(p, n * sizeof(value_type));
+#else
+ ::operator delete(p);
+#endif
}
}
@@ -1348,7 +1355,7 @@ class Map {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(InnerMap);
}; // end of class InnerMap
- typedef hash_map<Key, value_type*, hash<Key>, equal_to<Key>,
+ typedef hash_map<Key, value_type*, hash<Key>, std::equal_to<Key>,
MapAllocator<std::pair<const Key, MapPair<Key, T>*> > >
DeprecatedInnerMap;
diff --git a/src/google/protobuf/map_entry.h b/src/google/protobuf/map_entry.h
index e87eda64..abcd4529 100644
--- a/src/google/protobuf/map_entry.h
+++ b/src/google/protobuf/map_entry.h
@@ -158,8 +158,8 @@ class MapEntry : public MapEntryBase {
return entry_lite_.MergePartialFromCodedStream(input);
}
- int ByteSize() const {
- return entry_lite_.ByteSize();
+ size_t ByteSizeLong() const {
+ return entry_lite_.ByteSizeLong();
}
void SerializeWithCachedSizes(::google::protobuf::io::CodedOutputStream* output) const {
diff --git a/src/google/protobuf/map_entry_lite.h b/src/google/protobuf/map_entry_lite.h
index 4dedfd57..3fb58220 100644
--- a/src/google/protobuf/map_entry_lite.h
+++ b/src/google/protobuf/map_entry_lite.h
@@ -119,7 +119,7 @@ class MapEntryLite : public MessageLite {
kKeyFieldNumber, KeyTypeHandler::kWireType);
static const uint8 kValueTag = GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(
kValueFieldNumber, ValueTypeHandler::kWireType);
- static const int kTagSize = 1;
+ static const size_t kTagSize = 1;
public:
~MapEntryLite() {
@@ -201,8 +201,8 @@ class MapEntryLite : public MessageLite {
}
}
- int ByteSize() const {
- int size = 0;
+ size_t ByteSizeLong() const {
+ size_t size = 0;
size += has_key() ? kTagSize + KeyTypeHandler::ByteSize(key()) : 0;
size += has_value() ? kTagSize + ValueTypeHandler::ByteSize(value()) : 0;
return size;
diff --git a/src/google/protobuf/map_type_handler.h b/src/google/protobuf/map_type_handler.h
index 685a770f..a21c92d9 100644
--- a/src/google/protobuf/map_type_handler.h
+++ b/src/google/protobuf/map_type_handler.h
@@ -158,7 +158,7 @@ class MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type> {
MapWireFieldTypeTraits<WireFormatLite::TYPE_MESSAGE, Type>::kIsEnum;
// Functions used in parsing and serialization. ===================
- static inline int ByteSize(const MapEntryAccessorType& value);
+ static inline size_t ByteSize(const MapEntryAccessorType& value);
static inline int GetCachedSize(const MapEntryAccessorType& value);
static inline bool Read(io::CodedInputStream* input,
MapEntryAccessorType* value);
@@ -276,7 +276,7 @@ MAP_HANDLER(BOOL)
#undef MAP_HANDLER
template <typename Type>
-inline int
+inline size_t
MapTypeHandler<WireFormatLite::TYPE_MESSAGE, Type>::ByteSize(
const MapEntryAccessorType& value) {
return WireFormatLite::MessageSizeNoVirtual(value);
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc
index f18077dd..c8de458c 100644
--- a/src/google/protobuf/message.cc
+++ b/src/google/protobuf/message.cc
@@ -46,9 +46,9 @@
#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/map_field.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>
@@ -146,9 +146,9 @@ void Message::SerializeWithCachedSizes(
WireFormat::SerializeWithCachedSizes(*this, GetCachedSize(), output);
}
-int Message::ByteSize() const {
- int size = WireFormat::ByteSize(*this);
- SetCachedSize(size);
+size_t Message::ByteSizeLong() const {
+ size_t size = WireFormat::ByteSize(*this);
+ SetCachedSize(internal::ToCachedSize(size));
return size;
}
@@ -299,8 +299,8 @@ class GeneratedMessageFactory : public MessageFactory {
hash_map<const char*, RegistrationFunc*,
hash<const char*>, streq> file_map_;
- // Initialized lazily, so requires locking.
Mutex mutex_;
+ // Initialized lazily, so requires locking.
hash_map<const Descriptor*, const Message*> type_map_;
};
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h
index 9705e97e..bee25f77 100644
--- a/src/google/protobuf/message.h
+++ b/src/google/protobuf/message.h
@@ -271,10 +271,10 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
bool ParsePartialFromFileDescriptor(int file_descriptor);
// Parse a protocol buffer from a C++ istream. If successful, the entire
// input will be consumed.
- bool ParseFromIstream(istream* input);
+ bool ParseFromIstream(std::istream* input);
// Like ParseFromIstream(), but accepts messages that are missing
// required fields.
- bool ParsePartialFromIstream(istream* input);
+ bool ParsePartialFromIstream(std::istream* input);
// Serialize the message and write it to the given file descriptor. All
// required fields must be set.
@@ -283,9 +283,9 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
bool SerializePartialToFileDescriptor(int file_descriptor) const;
// Serialize the message and write it to the given C++ ostream. All
// required fields must be set.
- bool SerializeToOstream(ostream* output) const;
+ bool SerializeToOstream(std::ostream* output) const;
// Like SerializeToOstream(), but allows missing required fields.
- bool SerializePartialToOstream(ostream* output) const;
+ bool SerializePartialToOstream(std::ostream* output) const;
// Reflection-based methods ----------------------------------------
@@ -297,7 +297,7 @@ class LIBPROTOBUF_EXPORT Message : public MessageLite {
virtual bool IsInitialized() const;
virtual void CheckTypeAndMergeFrom(const MessageLite& other);
virtual bool MergePartialFromCodedStream(io::CodedInputStream* input);
- virtual int ByteSize() const;
+ virtual size_t ByteSizeLong() const;
virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const;
private:
diff --git a/src/google/protobuf/message_lite.cc b/src/google/protobuf/message_lite.cc
index ba56db95..9d6da264 100644
--- a/src/google/protobuf/message_lite.cc
+++ b/src/google/protobuf/message_lite.cc
@@ -33,8 +33,9 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
-#include <google/protobuf/message_lite.h>
#include <google/protobuf/arena.h>
+#include <google/protobuf/generated_message_util.h>
+#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h>
#include <string>
#include <google/protobuf/stubs/logging.h>
@@ -58,9 +59,9 @@ namespace {
// protobuf implementation but is more likely caused by concurrent modification
// of the message. This function attempts to distinguish between the two and
// provide a useful error message.
-void ByteSizeConsistencyError(int byte_size_before_serialization,
- int byte_size_after_serialization,
- int bytes_produced_by_serialization,
+void ByteSizeConsistencyError(size_t byte_size_before_serialization,
+ size_t byte_size_after_serialization,
+ size_t bytes_produced_by_serialization,
const MessageLite& message) {
GOOGLE_CHECK_EQ(byte_size_before_serialization, byte_size_after_serialization)
<< message.GetTypeName()
@@ -236,12 +237,15 @@ bool MessageLite::SerializeToCodedStream(io::CodedOutputStream* output) const {
return SerializePartialToCodedStream(output);
}
+size_t MessageLite::ByteSizeLong() const {
+ return internal::FromIntSize(ByteSize());
+}
+
bool MessageLite::SerializePartialToCodedStream(
io::CodedOutputStream* output) const {
- const int size = ByteSize(); // Force size to be cached.
- if (size < 0) {
- // Messages >2G cannot be serialized due to overflow computing ByteSize.
- GOOGLE_LOG(ERROR) << "Error computing ByteSize (possible overflow?).";
+ const size_t size = ByteSizeLong(); // Force size to be cached.
+ if (size > INT_MAX) {
+ GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB.";
return false;
}
@@ -249,7 +253,7 @@ bool MessageLite::SerializePartialToCodedStream(
if (buffer != NULL) {
uint8* end = SerializeWithCachedSizesToArray(buffer);
if (end - buffer != size) {
- ByteSizeConsistencyError(size, ByteSize(), end - buffer, *this);
+ ByteSizeConsistencyError(size, ByteSizeLong(), end - buffer, *this);
}
return true;
} else {
@@ -261,7 +265,7 @@ bool MessageLite::SerializePartialToCodedStream(
int final_byte_count = output->ByteCount();
if (final_byte_count - original_byte_count != size) {
- ByteSizeConsistencyError(size, ByteSize(),
+ ByteSizeConsistencyError(size, ByteSizeLong(),
final_byte_count - original_byte_count, *this);
}
@@ -287,11 +291,10 @@ bool MessageLite::AppendToString(string* output) const {
}
bool MessageLite::AppendPartialToString(string* output) const {
- int old_size = output->size();
- int byte_size = ByteSize();
- if (byte_size < 0) {
- // Messages >2G cannot be serialized due to overflow computing ByteSize.
- GOOGLE_LOG(ERROR) << "Error computing ByteSize (possible overflow?).";
+ size_t old_size = output->size();
+ size_t byte_size = ByteSizeLong();
+ if (byte_size > INT_MAX) {
+ GOOGLE_LOG(ERROR) << "Exceeded maximum protobuf size of 2GB.";
return false;
}
@@ -300,7 +303,7 @@ bool MessageLite::AppendPartialToString(string* output) const {
reinterpret_cast<uint8*>(io::mutable_string_data(output) + old_size);
uint8* end = SerializeWithCachedSizesToArray(start);
if (end - start != byte_size) {
- ByteSizeConsistencyError(byte_size, ByteSize(), end - start, *this);
+ ByteSizeConsistencyError(byte_size, ByteSizeLong(), end - start, *this);
}
return true;
}
@@ -321,12 +324,12 @@ bool MessageLite::SerializeToArray(void* data, int size) const {
}
bool MessageLite::SerializePartialToArray(void* data, int size) const {
- int byte_size = ByteSize();
+ int byte_size = ByteSizeLong();
if (size < byte_size) return false;
uint8* start = reinterpret_cast<uint8*>(data);
uint8* end = SerializeWithCachedSizesToArray(start);
if (end - start != byte_size) {
- ByteSizeConsistencyError(byte_size, ByteSize(), end - start, *this);
+ ByteSizeConsistencyError(byte_size, ByteSizeLong(), end - start, *this);
}
return true;
}
diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h
index 2bdfe496..88455669 100644
--- a/src/google/protobuf/message_lite.h
+++ b/src/google/protobuf/message_lite.h
@@ -239,12 +239,13 @@ class LIBPROTOBUF_EXPORT MessageLite {
bool AppendPartialToString(string* output) const;
// Computes the serialized size of the message. This recursively calls
- // ByteSize() on all embedded messages. If a subclass does not override
- // this, it MUST override SetCachedSize().
+ // ByteSize() on all embedded messages. Subclasses MUST override either
+ // ByteSize() or ByteSizeLong() (overriding both is fine).
//
// ByteSize() is generally linear in the number of fields defined for the
// proto.
- virtual int ByteSize() const = 0;
+ virtual int ByteSize() const { return static_cast<int>(ByteSizeLong()); }
+ virtual size_t ByteSizeLong() const;
// Serializes the message without recomputing the size. The message must
// not have changed since the last call to ByteSize(); if it has, the results
diff --git a/src/google/protobuf/message_unittest.cc b/src/google/protobuf/message_unittest.cc
index d668a1a6..3af05808 100644
--- a/src/google/protobuf/message_unittest.cc
+++ b/src/google/protobuf/message_unittest.cc
@@ -265,6 +265,24 @@ TEST(MessageTest, CheckOverflow) {
EXPECT_FALSE(message.AppendToCord(&serialized));
}
+TEST(MessageTest, CheckBigOverflow) {
+ unittest::TestAllTypes message;
+ // Create a message with size just over 4GB. We should be able to detect this
+ // too, even though it will make a plain "int" wrap back to a positive number.
+ const string data(1024, 'x');
+ Cord one_megabyte;
+ for (int i = 0; i < 1024; i++) {
+ one_megabyte.Append(data);
+ }
+
+ for (int i = 0; i < 4 * 1024 + 1; ++i) {
+ message.add_repeated_cord()->CopyFrom(one_megabyte);
+ }
+
+ Cord serialized;
+ EXPECT_FALSE(message.AppendToCord(&serialized));
+}
+
#endif // PROTOBUF_HAS_DEATH_TEST
namespace {
@@ -272,6 +290,12 @@ namespace {
class NegativeByteSize : public unittest::TestRequired {
public:
virtual int ByteSize() const { return -1; }
+
+ // The implementation of ByteSizeLong() from MessageLite, to simulate what
+ // would happen if TestRequired *hadn't* overridden it already.
+ virtual size_t ByteSizeLong() const {
+ return static_cast<unsigned int>(ByteSize());
+ }
};
} // namespace
@@ -319,6 +343,18 @@ TEST(MessageTest, ParseFailsOnInvalidMessageEnd) {
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());
+}
+
namespace {
void ExpectMessageMerged(const unittest::TestAllTypes& message) {
diff --git a/src/google/protobuf/metadata.h b/src/google/protobuf/metadata.h
index fdee150b..6e3eef63 100644
--- a/src/google/protobuf/metadata.h
+++ b/src/google/protobuf/metadata.h
@@ -152,10 +152,6 @@ class LIBPROTOBUF_EXPORT InternalMetadataWithArena {
}
};
-// Temporary compatibility typedef. Remove once this is released in components
-// and upb CL is submitted.
-typedef InternalMetadataWithArena InternalMetadata;
-
} // namespace internal
} // namespace protobuf
diff --git a/src/google/protobuf/reflection.h b/src/google/protobuf/reflection.h
index 2391f453..d5a6653c 100755
--- a/src/google/protobuf/reflection.h
+++ b/src/google/protobuf/reflection.h
@@ -80,6 +80,12 @@ class RepeatedFieldRef<
typedef IteratorType iterator;
typedef IteratorType const_iterator;
+ typedef T value_type;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef int size_type;
+ typedef ptrdiff_t difference_type;
+
iterator begin() const {
return iterator(data_, accessor_, true);
}
@@ -202,11 +208,18 @@ class RepeatedFieldRef<
typedef IteratorType iterator;
typedef IteratorType const_iterator;
+ typedef T value_type;
+ typedef T& reference;
+ typedef const T& const_reference;
+ typedef int size_type;
+ typedef ptrdiff_t difference_type;
+
iterator begin() const {
return iterator(data_, accessor_, true, NewMessage());
}
iterator end() const {
- return iterator(data_, accessor_, false, NewMessage());
+ // The end iterator must not be dereferenced, no need for scratch space.
+ return iterator(data_, accessor_, false, NULL);
}
private:
@@ -428,13 +441,13 @@ class RepeatedFieldRefIterator
public:
// Constructor for non-message fields.
RepeatedFieldRefIterator(const void* data,
- const RepeatedFieldAccessor* accessor,
- bool begin)
- : data_(data), accessor_(accessor),
- iterator_(begin ? accessor->BeginIterator(data) :
- accessor->EndIterator(data)),
- scratch_space_(new AccessorValueType) {
- }
+ const RepeatedFieldAccessor* accessor, bool begin)
+ : data_(data),
+ accessor_(accessor),
+ 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) {}
// Constructor for message fields.
RepeatedFieldRefIterator(const void* data,
const RepeatedFieldAccessor* accessor,
diff --git a/src/google/protobuf/reflection_ops.h b/src/google/protobuf/reflection_ops.h
index 4775911e..45d8c650 100644
--- a/src/google/protobuf/reflection_ops.h
+++ b/src/google/protobuf/reflection_ops.h
@@ -67,7 +67,7 @@ class LIBPROTOBUF_EXPORT ReflectionOps {
// the front of each name.
static void FindInitializationErrors(const Message& message,
const string& prefix,
- vector<string>* errors);
+ std::vector<string>* errors);
private:
// All methods are static. No need to construct.
diff --git a/src/google/protobuf/repeated_field.cc b/src/google/protobuf/repeated_field.cc
index 77004f59..5ca964c1 100644
--- a/src/google/protobuf/repeated_field.cc
+++ b/src/google/protobuf/repeated_field.cc
@@ -58,14 +58,16 @@ void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) {
(std::numeric_limits<size_t>::max() - kRepHeaderSize) /
sizeof(old_rep->elements[0]))
<< "Requested size is too large to fit into size_t.";
+ size_t bytes = kRepHeaderSize + sizeof(old_rep->elements[0]) * new_size;
if (arena == NULL) {
- rep_ = reinterpret_cast<Rep*>(
- new char[kRepHeaderSize + sizeof(old_rep->elements[0]) * new_size]);
+ rep_ = reinterpret_cast<Rep*>(::operator new(bytes));
} else {
rep_ = reinterpret_cast<Rep*>(
- ::google::protobuf::Arena::CreateArray<char>(arena,
- kRepHeaderSize + sizeof(old_rep->elements[0]) * new_size));
+ ::google::protobuf::Arena::CreateArray<char>(arena, bytes));
}
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ const int old_total_size = total_size_;
+#endif
total_size_ = new_size;
if (old_rep && old_rep->allocated_size > 0) {
memcpy(rep_->elements, old_rep->elements,
@@ -75,7 +77,13 @@ void** RepeatedPtrFieldBase::InternalExtend(int extend_amount) {
rep_->allocated_size = 0;
}
if (arena == NULL) {
- delete [] reinterpret_cast<char*>(old_rep);
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ const size_t old_size =
+ old_total_size * sizeof(rep_->elements[0]) + kRepHeaderSize;
+ ::operator delete(static_cast<void*>(old_rep), old_size);
+#else
+ ::operator delete(static_cast<void*>(old_rep));
+#endif
}
return &rep_->elements[current_size_];
}
diff --git a/src/google/protobuf/repeated_field.h b/src/google/protobuf/repeated_field.h
index bc567555..6ede0e1a 100644
--- a/src/google/protobuf/repeated_field.h
+++ b/src/google/protobuf/repeated_field.h
@@ -120,6 +120,10 @@ class RepeatedField {
const Element& Get(int index) const;
Element* Mutable(int index);
+
+ const Element& operator[](int index) const { return Get(index); }
+ Element& operator[](int index) { return *Mutable(index); }
+
void Set(int index, const Element& value);
void Add(const Element& value);
Element* Add();
@@ -134,6 +138,7 @@ class RepeatedField {
void Clear();
void MergeFrom(const RepeatedField& other);
+ void UnsafeMergeFrom(const RepeatedField& other);
void CopyFrom(const RepeatedField& other);
// Reserve space to expand the field to at least the given size. If the
@@ -284,7 +289,12 @@ class RepeatedField {
e->Element::~Element();
}
if (rep->arena == NULL) {
- delete[] reinterpret_cast<char*>(rep);
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ const size_t bytes = size * sizeof(*e) + kRepHeaderSize;
+ ::operator delete(static_cast<void*>(rep), bytes);
+#else
+ ::operator delete(static_cast<void*>(rep));
+#endif
}
}
}
@@ -671,17 +681,7 @@ inline const Message& GenericTypeHandler<Message>::default_instance() {
return *null;
}
-
-// HACK: If a class is declared as DLL-exported in MSVC, it insists on
-// generating copies of all its methods -- even inline ones -- to include
-// in the DLL. But SpaceUsed() calls StringSpaceUsedExcludingSelf() which
-// isn't in the lite library, therefore the lite library cannot link if
-// StringTypeHandler is exported. So, we factor out StringTypeHandlerBase,
-// export that, then make StringTypeHandler be a subclass which is NOT
-// exported.
-// TODO(kenton): Now that StringSpaceUsedExcludingSelf() is in the lite
-// library, this can be cleaned up.
-class LIBPROTOBUF_EXPORT StringTypeHandlerBase {
+class LIBPROTOBUF_EXPORT StringTypeHandler {
public:
typedef string Type;
@@ -708,10 +708,6 @@ class LIBPROTOBUF_EXPORT StringTypeHandlerBase {
static inline const Type& default_instance() {
return ::google::protobuf::internal::GetEmptyString();
}
-};
-
-class StringTypeHandler : public StringTypeHandlerBase {
- public:
static int SpaceUsed(const string& value) {
return static_cast<int>(sizeof(value)) + StringSpaceUsedExcludingSelf(value);
}
@@ -742,6 +738,9 @@ class RepeatedPtrField : public internal::RepeatedPtrFieldBase {
Element* Mutable(int index);
Element* Add();
+ const Element& operator[](int index) const { return Get(index); }
+ Element& operator[](int index) { return *Mutable(index); }
+
// Remove the last element in the array.
// Ownership of the element is retained by the array.
void RemoveLast();
@@ -753,6 +752,7 @@ class RepeatedPtrField : public internal::RepeatedPtrFieldBase {
void Clear();
void MergeFrom(const RepeatedPtrField& other);
+ void UnsafeMergeFrom(const RepeatedPtrField& other) { MergeFrom(other); }
void CopyFrom(const RepeatedPtrField& other);
// Reserve space to expand the field to at least the given size. This only
@@ -1138,8 +1138,7 @@ inline void RepeatedField<Element>::Clear() {
}
template <typename Element>
-inline void RepeatedField<Element>::MergeFrom(const RepeatedField& other) {
- GOOGLE_CHECK_NE(&other, this);
+inline void RepeatedField<Element>::UnsafeMergeFrom(const RepeatedField& other) {
if (other.current_size_ != 0) {
Reserve(current_size_ + other.current_size_);
CopyArray(rep_->elements + current_size_,
@@ -1149,6 +1148,12 @@ inline void RepeatedField<Element>::MergeFrom(const RepeatedField& other) {
}
template <typename Element>
+inline void RepeatedField<Element>::MergeFrom(const RepeatedField& other) {
+ GOOGLE_CHECK_NE(&other, this);
+ UnsafeMergeFrom(other);
+}
+
+template <typename Element>
inline void RepeatedField<Element>::CopyFrom(const RepeatedField& other) {
if (&other == this) return;
Clear();
@@ -1265,13 +1270,12 @@ void RepeatedField<Element>::Reserve(int new_size) {
(std::numeric_limits<size_t>::max() - kRepHeaderSize) /
sizeof(Element))
<< "Requested size is too large to fit into size_t.";
+ size_t bytes = kRepHeaderSize + sizeof(Element) * new_size;
if (arena == NULL) {
- rep_ = reinterpret_cast<Rep*>(
- new char[kRepHeaderSize + sizeof(Element) * new_size]);
+ rep_ = static_cast<Rep*>(::operator new(bytes));
} else {
rep_ = reinterpret_cast<Rep*>(
- ::google::protobuf::Arena::CreateArray<char>(arena,
- kRepHeaderSize + sizeof(Element) * new_size));
+ ::google::protobuf::Arena::CreateArray<char>(arena, bytes));
}
rep_->arena = arena;
int old_total_size = total_size_;
@@ -1363,7 +1367,12 @@ void RepeatedPtrFieldBase::Destroy() {
for (int i = 0; i < n; i++) {
TypeHandler::Delete(cast<TypeHandler>(elements[i]), NULL);
}
- delete[] reinterpret_cast<char*>(rep_);
+#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation)
+ const size_t size = total_size_ * sizeof(elements[0]) + kRepHeaderSize;
+ ::operator delete(static_cast<void*>(rep_), size);
+#else
+ ::operator delete(static_cast<void*>(rep_));
+#endif
}
rep_ = NULL;
}
diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc
index 39b24b33..33547146 100644
--- a/src/google/protobuf/repeated_field_unittest.cc
+++ b/src/google/protobuf/repeated_field_unittest.cc
@@ -95,7 +95,7 @@ TEST(RepeatedField, Small) {
EXPECT_EQ(field.size(), 0);
// Additional bytes are for 'struct Rep' header.
int expected_usage = 4 * sizeof(int) + sizeof(Arena*);
- EXPECT_EQ(field.SpaceUsedExcludingSelf(), expected_usage);
+ EXPECT_GE(field.SpaceUsedExcludingSelf(), expected_usage);
}
@@ -207,7 +207,7 @@ TEST(RepeatedField, ReserveMoreThanDouble) {
RepeatedField<int> field;
field.Reserve(20);
- EXPECT_EQ(20, ReservedSpace(&field));
+ EXPECT_LE(20, ReservedSpace(&field));
}
TEST(RepeatedField, ReserveLessThanDouble) {
@@ -215,9 +215,10 @@ TEST(RepeatedField, ReserveLessThanDouble) {
// field to grow by double instead.
RepeatedField<int> field;
field.Reserve(20);
- field.Reserve(30);
+ int capacity = field.Capacity();
+ field.Reserve(capacity * 1.5);
- EXPECT_EQ(40, ReservedSpace(&field));
+ EXPECT_LE(2 * capacity, ReservedSpace(&field));
}
TEST(RepeatedField, ReserveLessThanExisting) {
@@ -229,7 +230,7 @@ TEST(RepeatedField, ReserveLessThanExisting) {
field.Reserve(10);
EXPECT_EQ(previous_ptr, field.data());
- EXPECT_EQ(20, ReservedSpace(&field));
+ EXPECT_LE(20, ReservedSpace(&field));
}
TEST(RepeatedField, Resize) {
@@ -397,6 +398,16 @@ TEST(RepeatedField, MutableDataIsMutable) {
EXPECT_EQ(2, field.Get(0));
}
+TEST(RepeatedField, SubscriptOperators) {
+ RepeatedField<int> field;
+ field.Add(1);
+ EXPECT_EQ(1, field.Get(0));
+ EXPECT_EQ(1, field[0]);
+ EXPECT_EQ(field.Mutable(0), &field[0]);
+ const RepeatedField<int>& const_field = field;
+ EXPECT_EQ(field.data(), &const_field[0]);
+}
+
TEST(RepeatedField, Truncate) {
RepeatedField<int> field;
@@ -470,11 +481,11 @@ TEST(RepeatedField, ClearThenReserveMore) {
EXPECT_EQ(32, field.size());
field.Clear();
EXPECT_EQ(0, field.size());
- EXPECT_EQ(32, field.Capacity());
+ EXPECT_LE(32, field.Capacity());
field.Reserve(1024);
EXPECT_EQ(0, field.size());
- EXPECT_EQ(1024, field.Capacity());
+ EXPECT_LE(1024, field.Capacity());
// Finish test -- |field| should destroy the cleared-but-not-yet-destroyed
// strings.
}
@@ -629,15 +640,18 @@ TEST(RepeatedPtrField, ReserveMoreThanDouble) {
RepeatedPtrField<string> field;
field.Reserve(20);
- EXPECT_EQ(20, ReservedSpace(&field));
+ EXPECT_LE(20, ReservedSpace(&field));
}
TEST(RepeatedPtrField, ReserveLessThanDouble) {
RepeatedPtrField<string> field;
field.Reserve(20);
- field.Reserve(30);
- EXPECT_EQ(40, ReservedSpace(&field));
+ int capacity = field.Capacity();
+ // Grow by 1.5x
+ field.Reserve(capacity + (capacity >> 2));
+
+ EXPECT_LE(2 * capacity, ReservedSpace(&field));
}
TEST(RepeatedPtrField, ReserveLessThanExisting) {
@@ -647,7 +661,7 @@ TEST(RepeatedPtrField, ReserveLessThanExisting) {
field.Reserve(10);
EXPECT_EQ(previous_ptr, field.data());
- EXPECT_EQ(20, ReservedSpace(&field));
+ EXPECT_LE(20, ReservedSpace(&field));
}
TEST(RepeatedPtrField, ReserveDoesntLoseAllocated) {
@@ -918,6 +932,16 @@ TEST(RepeatedPtrField, MutableDataIsMutable) {
EXPECT_EQ("2", field.Get(0));
}
+TEST(RepeatedPtrField, SubscriptOperators) {
+ RepeatedPtrField<string> field;
+ *field.Add() = "1";
+ EXPECT_EQ("1", field.Get(0));
+ EXPECT_EQ("1", field[0]);
+ EXPECT_EQ(field.Mutable(0), &field[0]);
+ const RepeatedPtrField<string>& const_field = field;
+ EXPECT_EQ(*field.data(), &const_field[0]);
+}
+
TEST(RepeatedPtrField, ExtractSubrange) {
// Exhaustively test every subrange in arrays of all sizes from 0 through 9
// with 0 through 3 cleared elements at the end.
diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc
index 5cc77bf3..951a0bcc 100644
--- a/src/google/protobuf/source_context.pb.cc
+++ b/src/google/protobuf/source_context.pb.cc
@@ -43,20 +43,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() {
SourceContext_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
SourceContext_descriptor_,
- SourceContext::default_instance_,
+ SourceContext::internal_default_instance(),
SourceContext_offsets_,
-1,
-1,
-1,
sizeof(SourceContext),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SourceContext, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto);
}
@@ -65,36 +64,49 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- SourceContext_descriptor_, &SourceContext::default_instance());
+ SourceContext_descriptor_, SourceContext::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- delete SourceContext::default_instance_;
+ SourceContext_default_instance_.Shutdown();
delete SourceContext_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ ::google::protobuf::internal::GetEmptyString();
+ SourceContext_default_instance_.DefaultConstruct();
+ SourceContext_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n$google/protobuf/source_context.proto\022\017"
"google.protobuf\"\"\n\rSourceContext\022\021\n\tfile"
- "_name\030\001 \001(\tBU\n\023com.google.protobufB\022Sour"
- "ceContextProtoP\001\240\001\001\242\002\003GPB\252\002\036Google.Proto"
- "buf.WellKnownTypesb\006proto3", 186);
+ "_name\030\001 \001(\tBR\n\023com.google.protobufB\022Sour"
+ "ceContextProtoP\001\242\002\003GPB\252\002\036Google.Protobuf"
+ ".WellKnownTypesb\006proto3", 183);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/source_context.proto", &protobuf_RegisterTypes);
- SourceContext::default_instance_ = new SourceContext();
- SourceContext::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto() {
@@ -102,6 +114,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fsource_5fcontext_2eproto
}
} static_descriptor_initializer_google_2fprotobuf_2fsource_5fcontext_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -110,27 +132,25 @@ const int SourceContext::kFileNameFieldNumber;
SourceContext::SourceContext()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.SourceContext)
}
void SourceContext::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
SourceContext::SourceContext(const SourceContext& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.SourceContext)
}
void SourceContext::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
file_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _cached_size_ = 0;
}
SourceContext::~SourceContext() {
@@ -140,8 +160,6 @@ SourceContext::~SourceContext() {
void SourceContext::SharedDtor() {
file_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
- }
}
void SourceContext::SetCachedSize(int size) const {
@@ -155,11 +173,11 @@ const ::google::protobuf::Descriptor* SourceContext::descriptor() {
}
const SourceContext& SourceContext::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ return *internal_default_instance();
}
-SourceContext* SourceContext::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<SourceContext> SourceContext_default_instance_;
SourceContext* SourceContext::New(::google::protobuf::Arena* arena) const {
SourceContext* n = new SourceContext;
@@ -239,6 +257,7 @@ void SourceContext::SerializeWithCachedSizes(
::google::protobuf::uint8* SourceContext::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.SourceContext)
// optional string file_name = 1;
if (this->file_name().size() > 0) {
@@ -255,9 +274,9 @@ void SourceContext::SerializeWithCachedSizes(
return target;
}
-int SourceContext::ByteSize() const {
+size_t SourceContext::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.SourceContext)
- int total_size = 0;
+ size_t total_size = 0;
// optional string file_name = 1;
if (this->file_name().size() > 0) {
@@ -266,18 +285,17 @@ int SourceContext::ByteSize() const {
this->file_name());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SourceContext::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.SourceContext)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const SourceContext* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const SourceContext* source =
::google::protobuf::internal::DynamicCastToGenerated<const SourceContext>(
&from);
if (source == NULL) {
@@ -285,15 +303,21 @@ void SourceContext::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.SourceContext)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void SourceContext::MergeFrom(const SourceContext& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.SourceContext)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void SourceContext::UnsafeMergeFrom(const SourceContext& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.file_name().size() > 0) {
file_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.file_name_);
@@ -311,7 +335,7 @@ void SourceContext::CopyFrom(const SourceContext& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.SourceContext)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool SourceContext::IsInitialized() const {
@@ -344,37 +368,37 @@ void SourceContext::InternalSwap(SourceContext* other) {
void SourceContext::clear_file_name() {
file_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- const ::std::string& SourceContext::file_name() const {
+const ::std::string& SourceContext::file_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name)
return file_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void SourceContext::set_file_name(const ::std::string& value) {
+void SourceContext::set_file_name(const ::std::string& value) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name)
}
- void SourceContext::set_file_name(const char* value) {
+void SourceContext::set_file_name(const char* value) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.SourceContext.file_name)
}
- void SourceContext::set_file_name(const char* value, size_t size) {
+void SourceContext::set_file_name(const char* value, size_t size) {
file_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceContext.file_name)
}
- ::std::string* SourceContext::mutable_file_name() {
+::std::string* SourceContext::mutable_file_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.SourceContext.file_name)
return file_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* SourceContext::release_file_name() {
+::std::string* SourceContext::release_file_name() {
// @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name)
return file_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void SourceContext::set_allocated_file_name(::std::string* file_name) {
+void SourceContext::set_allocated_file_name(::std::string* file_name) {
if (file_name != NULL) {
} else {
@@ -384,6 +408,9 @@ void SourceContext::clear_file_name() {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
}
+inline const SourceContext* SourceContext::internal_default_instance() {
+ return &SourceContext_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h
index 341a4534..18a56941 100644
--- a/src/google/protobuf/source_context.pb.h
+++ b/src/google/protobuf/source_context.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -34,6 +34,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto();
@@ -56,6 +57,8 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
static const ::google::protobuf::Descriptor* descriptor();
static const SourceContext& default_instance();
+ static const SourceContext* internal_default_instance();
+
void Swap(SourceContext* other);
// implements Message ----------------------------------------------
@@ -70,7 +73,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -86,6 +89,7 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(SourceContext* other);
+ void UnsafeMergeFrom(const SourceContext& from);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -116,16 +120,17 @@ class LIBPROTOBUF_EXPORT SourceContext : public ::google::protobuf::Message /* @
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
::google::protobuf::internal::ArenaStringPtr file_name_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fsource_5fcontext_2eproto();
void InitAsDefaultInstance();
- static SourceContext* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<SourceContext> SourceContext_default_instance_;
+
// ===================================================================
@@ -178,6 +183,9 @@ inline void SourceContext::set_allocated_file_name(::std::string* file_name) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
}
+inline const SourceContext* SourceContext::internal_default_instance() {
+ return &SourceContext_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/source_context.proto b/src/google/protobuf/source_context.proto
index a2c08e2b..79137ce8 100644
--- a/src/google/protobuf/source_context.proto
+++ b/src/google/protobuf/source_context.proto
@@ -36,7 +36,6 @@ option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option java_package = "com.google.protobuf";
option java_outer_classname = "SourceContextProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// `SourceContext` represents information about the source of a
diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc
index a551384c..c8f5af90 100644
--- a/src/google/protobuf/struct.pb.cc
+++ b/src/google/protobuf/struct.pb.cc
@@ -59,14 +59,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto() {
Struct_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Struct_descriptor_,
- Struct::default_instance_,
+ Struct::internal_default_instance(),
Struct_offsets_,
-1,
-1,
-1,
sizeof(Struct),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Struct, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Struct, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Struct, _internal_metadata_));
Struct_FieldsEntry_descriptor_ = Struct_descriptor_->nested_type(0);
Value_descriptor_ = file->message_type(1);
static const int Value_offsets_[7] = {
@@ -81,7 +80,7 @@ void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto() {
Value_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Value_descriptor_,
- Value::default_instance_,
+ Value::internal_default_instance(),
Value_offsets_,
-1,
-1,
@@ -89,8 +88,7 @@ void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto() {
Value_default_oneof_instance_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, _oneof_case_[0]),
sizeof(Value),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Value, _internal_metadata_));
ListValue_descriptor_ = file->message_type(2);
static const int ListValue_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListValue, values_),
@@ -98,21 +96,20 @@ void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto() {
ListValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
ListValue_descriptor_,
- ListValue::default_instance_,
+ ListValue::internal_default_instance(),
ListValue_offsets_,
-1,
-1,
-1,
sizeof(ListValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ListValue, _internal_metadata_));
NullValue_descriptor_ = file->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto);
}
@@ -121,7 +118,7 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Struct_descriptor_, &Struct::default_instance());
+ Struct_descriptor_, Struct::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
Struct_FieldsEntry_descriptor_,
::google::protobuf::internal::MapEntry<
@@ -132,30 +129,46 @@ void protobuf_RegisterTypes(const ::std::string&) {
0>::CreateDefaultInstance(
Struct_FieldsEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Value_descriptor_, &Value::default_instance());
+ Value_descriptor_, Value::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- ListValue_descriptor_, &ListValue::default_instance());
+ ListValue_descriptor_, ListValue::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto() {
- delete Struct::default_instance_;
+ Struct_default_instance_.Shutdown();
delete Struct_reflection_;
- delete Value::default_instance_;
+ Value_default_instance_.Shutdown();
delete Value_default_oneof_instance_;
delete Value_reflection_;
- delete ListValue::default_instance_;
+ ListValue_default_instance_.Shutdown();
delete ListValue_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ ::google::protobuf::internal::GetEmptyString();
+ Struct_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ Value_default_instance_.DefaultConstruct();
+ Value_default_oneof_instance_ = new ValueOneofInstance();
+ ListValue_default_instance_.DefaultConstruct();
+ Struct_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Value_default_instance_.get_mutable()->InitAsDefaultInstance();
+ ListValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\034google/protobuf/struct.proto\022\017google.p"
"rotobuf\"\204\001\n\006Struct\0223\n\006fields\030\001 \003(\0132#.goo"
@@ -171,21 +184,19 @@ void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto() {
"es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull"
"Value\022\016\n\nNULL_VALUE\020\000B\201\001\n\023com.google.pro"
"tobufB\013StructProtoP\001Z1github.com/golang/"
- "protobuf/ptypes/struct;structpb\240\001\001\242\002\003GPB"
+ "protobuf/ptypes/struct;structpb\370\001\001\242\002\003GPB"
"\252\002\036Google.Protobuf.WellKnownTypesb\006proto"
"3", 641);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/struct.proto", &protobuf_RegisterTypes);
- Struct::default_instance_ = new Struct();
- Value::default_instance_ = new Value();
- Value_default_oneof_instance_ = new ValueOneofInstance();
- ListValue::default_instance_ = new ListValue();
- Struct::default_instance_->InitAsDefaultInstance();
- Value::default_instance_->InitAsDefaultInstance();
- ListValue::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fstruct_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fstruct_2eproto() {
@@ -197,7 +208,7 @@ const ::google::protobuf::EnumDescriptor* NullValue_descriptor() {
return NullValue_descriptor_;
}
bool NullValue_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 0:
return true;
default:
@@ -206,6 +217,16 @@ bool NullValue_IsValid(int value) {
}
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -214,30 +235,39 @@ const int Struct::kFieldsFieldNumber;
Struct::Struct()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Struct)
}
+Struct::Struct(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ fields_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Struct)
+}
void Struct::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Struct::Struct(const Struct& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Struct)
}
void Struct::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
fields_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
fields_.SetEntryDescriptor(
&::google::protobuf::Struct_FieldsEntry_descriptor_);
+ _cached_size_ = 0;
}
Struct::~Struct() {
@@ -246,10 +276,19 @@ Struct::~Struct() {
}
void Struct::SharedDtor() {
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
}
+
}
+void Struct::ArenaDtor(void* object) {
+ Struct* _this = reinterpret_cast< Struct* >(object);
+ (void)_this;
+}
+void Struct::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Struct::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -261,18 +300,14 @@ const ::google::protobuf::Descriptor* Struct::descriptor() {
}
const Struct& Struct::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ return *internal_default_instance();
}
-Struct* Struct::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Struct> Struct_default_instance_;
Struct* Struct::New(::google::protobuf::Arena* arena) const {
- Struct* n = new Struct;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Struct>(arena);
}
void Struct::Clear() {
@@ -373,6 +408,9 @@ void Struct::SerializeWithCachedSizes(
items[i]->first, items[i]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
+ if (entry->GetArena() != NULL) {
+ entry.release();
+ }
Utf8Check::Check(items[i]);
}
} else {
@@ -384,6 +422,9 @@ void Struct::SerializeWithCachedSizes(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
+ if (entry->GetArena() != NULL) {
+ entry.release();
+ }
Utf8Check::Check(&*it);
}
}
@@ -394,6 +435,7 @@ void Struct::SerializeWithCachedSizes(
::google::protobuf::uint8* Struct::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Struct)
// map<string, .google.protobuf.Value> fields = 1;
if (!this->fields().empty()) {
@@ -430,6 +472,9 @@ void Struct::SerializeWithCachedSizes(
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
+ if (entry->GetArena() != NULL) {
+ entry.release();
+ }
Utf8Check::Check(items[i]);
}
} else {
@@ -443,6 +488,9 @@ void Struct::SerializeWithCachedSizes(
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
+ if (entry->GetArena() != NULL) {
+ entry.release();
+ }
Utf8Check::Check(&*it);
}
}
@@ -452,35 +500,41 @@ void Struct::SerializeWithCachedSizes(
return target;
}
-int Struct::ByteSize() const {
+size_t Struct::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Struct)
- int total_size = 0;
+ size_t total_size = 0;
// map<string, .google.protobuf.Value> fields = 1;
- total_size += 1 * this->fields_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->fields_size());
{
::google::protobuf::scoped_ptr<Struct_FieldsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::google::protobuf::Value >::const_iterator
it = this->fields().begin();
it != this->fields().end(); ++it) {
+ if (entry.get() != NULL && entry->GetArena() != NULL) {
+ entry.release();
+ }
entry.reset(fields_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
+ if (entry.get() != NULL && entry->GetArena() != NULL) {
+ entry.release();
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Struct::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Struct)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Struct* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Struct* source =
::google::protobuf::internal::DynamicCastToGenerated<const Struct>(
&from);
if (source == NULL) {
@@ -488,15 +542,21 @@ void Struct::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Struct)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Struct::MergeFrom(const Struct& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Struct)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Struct::UnsafeMergeFrom(const Struct& from) {
+ GOOGLE_DCHECK(&from != this);
fields_.MergeFrom(from.fields_);
}
@@ -511,7 +571,7 @@ void Struct::CopyFrom(const Struct& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Struct)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Struct::IsInitialized() const {
@@ -521,6 +581,18 @@ bool Struct::IsInitialized() const {
void Struct::Swap(Struct* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Struct temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Struct::UnsafeArenaSwap(Struct* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Struct::InternalSwap(Struct* other) {
@@ -558,6 +630,9 @@ Struct::mutable_fields() {
return fields_.MutableMap();
}
+inline const Struct* Struct::internal_default_instance() {
+ return &Struct_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -573,33 +648,43 @@ const int Value::kListValueFieldNumber;
Value::Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Value)
}
+Value::Value(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Value)
+}
void Value::InitAsDefaultInstance() {
- _is_default_instance_ = true;
Value_default_oneof_instance_->null_value_ = 0;
Value_default_oneof_instance_->number_value_ = 0;
Value_default_oneof_instance_->string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
Value_default_oneof_instance_->bool_value_ = false;
- Value_default_oneof_instance_->struct_value_ = const_cast< ::google::protobuf::Struct*>(&::google::protobuf::Struct::default_instance());
- Value_default_oneof_instance_->list_value_ = const_cast< ::google::protobuf::ListValue*>(&::google::protobuf::ListValue::default_instance());
+ Value_default_oneof_instance_->struct_value_ = const_cast< ::google::protobuf::Struct*>(
+ ::google::protobuf::Struct::internal_default_instance());
+ Value_default_oneof_instance_->list_value_ = const_cast< ::google::protobuf::ListValue*>(
+ ::google::protobuf::ListValue::internal_default_instance());
}
Value::Value(const Value& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Value)
}
void Value::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
clear_has_kind();
+ _cached_size_ = 0;
}
Value::~Value() {
@@ -608,13 +693,22 @@ Value::~Value() {
}
void Value::SharedDtor() {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
+ }
+
if (has_kind()) {
clear_kind();
}
- if (this != default_instance_) {
- }
}
+void Value::ArenaDtor(void* object) {
+ Value* _this = reinterpret_cast< Value* >(object);
+ (void)_this;
+}
+void Value::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Value::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -626,23 +720,19 @@ const ::google::protobuf::Descriptor* Value::descriptor() {
}
const Value& Value::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ return *internal_default_instance();
}
-Value* Value::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Value> Value_default_instance_;
Value* Value::New(::google::protobuf::Arena* arena) const {
- Value* n = new Value;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Value>(arena);
}
void Value::clear_kind() {
// @@protoc_insertion_point(one_of_clear_start:google.protobuf.Value)
- switch(kind_case()) {
+ switch (kind_case()) {
case kNullValue: {
// No need to clear
break;
@@ -652,7 +742,8 @@ void Value::clear_kind() {
break;
}
case kStringValue: {
- kind_.string_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ kind_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
break;
}
case kBoolValue: {
@@ -660,11 +751,15 @@ void Value::clear_kind() {
break;
}
case kStructValue: {
- delete kind_.struct_value_;
+ if (GetArenaNoVirtual() == NULL) {
+ delete kind_.struct_value_;
+ }
break;
}
case kListValue: {
- delete kind_.list_value_;
+ if (GetArenaNoVirtual() == NULL) {
+ delete kind_.list_value_;
+ }
break;
}
case KIND_NOT_SET: {
@@ -701,14 +796,13 @@ bool Value::MergePartialFromCodedStream(
} else {
goto handle_unusual;
}
- if (input->ExpectTag(17)) goto parse_number_value;
+ goto after_list_value;
break;
}
// optional double number_value = 2;
case 2: {
if (tag == 17) {
- parse_number_value:
clear_kind();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
@@ -717,14 +811,13 @@ bool Value::MergePartialFromCodedStream(
} else {
goto handle_unusual;
}
- if (input->ExpectTag(26)) goto parse_string_value;
+ goto after_list_value;
break;
}
// optional string string_value = 3;
case 3: {
if (tag == 26) {
- parse_string_value:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_string_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
@@ -734,14 +827,13 @@ bool Value::MergePartialFromCodedStream(
} else {
goto handle_unusual;
}
- if (input->ExpectTag(32)) goto parse_bool_value;
+ goto after_list_value;
break;
}
// optional bool bool_value = 4;
case 4: {
if (tag == 32) {
- parse_bool_value:
clear_kind();
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
@@ -750,14 +842,13 @@ bool Value::MergePartialFromCodedStream(
} else {
goto handle_unusual;
}
- if (input->ExpectTag(42)) goto parse_struct_value;
+ goto after_list_value;
break;
}
// optional .google.protobuf.Struct struct_value = 5;
case 5: {
if (tag == 42) {
- parse_struct_value:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_struct_value()));
} else {
@@ -776,6 +867,7 @@ bool Value::MergePartialFromCodedStream(
} else {
goto handle_unusual;
}
+ after_list_value:
if (input->ExpectAtEnd()) goto success;
break;
}
@@ -847,6 +939,7 @@ void Value::SerializeWithCachedSizes(
::google::protobuf::uint8* Value::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Value)
// optional .google.protobuf.NullValue null_value = 1;
if (has_null_value()) {
@@ -893,9 +986,9 @@ void Value::SerializeWithCachedSizes(
return target;
}
-int Value::ByteSize() const {
+size_t Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Value)
- int total_size = 0;
+ size_t total_size = 0;
switch (kind_case()) {
// optional .google.protobuf.NullValue null_value = 1;
@@ -939,18 +1032,17 @@ int Value::ByteSize() const {
break;
}
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Value* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Value* source =
::google::protobuf::internal::DynamicCastToGenerated<const Value>(
&from);
if (source == NULL) {
@@ -958,15 +1050,21 @@ void Value::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Value)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Value::MergeFrom(const Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Value::UnsafeMergeFrom(const Value& from) {
+ GOOGLE_DCHECK(&from != this);
switch (from.kind_case()) {
case kNullValue: {
set_null_value(from.null_value());
@@ -1009,7 +1107,7 @@ void Value::CopyFrom(const Value& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Value)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Value::IsInitialized() const {
@@ -1019,6 +1117,18 @@ bool Value::IsInitialized() const {
void Value::Swap(Value* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Value temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Value::UnsafeArenaSwap(Value* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Value::InternalSwap(Value* other) {
@@ -1052,14 +1162,14 @@ void Value::clear_null_value() {
clear_has_kind();
}
}
- ::google::protobuf::NullValue Value::null_value() const {
+::google::protobuf::NullValue Value::null_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Value.null_value)
if (has_null_value()) {
return static_cast< ::google::protobuf::NullValue >(kind_.null_value_);
}
return static_cast< ::google::protobuf::NullValue >(0);
}
- void Value::set_null_value(::google::protobuf::NullValue value) {
+void Value::set_null_value(::google::protobuf::NullValue value) {
if (!has_null_value()) {
clear_kind();
set_has_null_value();
@@ -1081,14 +1191,14 @@ void Value::clear_number_value() {
clear_has_kind();
}
}
- double Value::number_value() const {
+double Value::number_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Value.number_value)
if (has_number_value()) {
return kind_.number_value_;
}
return 0;
}
- void Value::set_number_value(double value) {
+void Value::set_number_value(double value) {
if (!has_number_value()) {
clear_kind();
set_has_number_value();
@@ -1106,77 +1216,105 @@ void Value::set_has_string_value() {
}
void Value::clear_string_value() {
if (has_string_value()) {
- kind_.string_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ kind_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
clear_has_kind();
}
}
- const ::std::string& Value::string_value() const {
+const ::std::string& Value::string_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Value.string_value)
if (has_string_value()) {
- return kind_.string_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return kind_.string_value_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
return *&::google::protobuf::internal::GetEmptyStringAlreadyInited();
}
- void Value::set_string_value(const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
+void Value::set_string_value(const ::std::string& value) {
if (!has_string_value()) {
clear_kind();
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
}
- void Value::set_string_value(const char* value) {
+void Value::set_string_value(const char* value) {
if (!has_string_value()) {
clear_kind();
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(value));
+ kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ ::std::string(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Value.string_value)
}
- void Value::set_string_value(const char* value, size_t size) {
+void Value::set_string_value(const char* value,
+ size_t size) {
if (!has_string_value()) {
clear_kind();
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size));
+ kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Value.string_value)
}
- ::std::string* Value::mutable_string_value() {
+::std::string* Value::mutable_string_value() {
if (!has_string_value()) {
clear_kind();
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+ return kind_.string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.string_value)
- return kind_.string_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- ::std::string* Value::release_string_value() {
+::std::string* Value::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.string_value)
if (has_string_value()) {
clear_has_kind();
- return kind_.string_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return kind_.string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
} else {
return NULL;
}
}
- void Value::set_allocated_string_value(::std::string* string_value) {
+::std::string* Value::unsafe_arena_release_string_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (has_string_value()) {
+ clear_has_kind();
+ return kind_.string_value_.UnsafeArenaRelease(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ } else {
+ return NULL;
+ }
+}
+void Value::set_allocated_string_value(::std::string* string_value) {
if (!has_string_value()) {
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
clear_kind();
if (string_value != NULL) {
set_has_string_value();
- kind_.string_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- string_value);
+ kind_.string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value,
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value)
}
+void Value::unsafe_arena_set_allocated_string_value(::std::string* string_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (!has_string_value()) {
+ kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ clear_kind();
+ if (string_value) {
+ set_has_string_value();
+ kind_.string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual());
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.string_value)
+}
// optional bool bool_value = 4;
bool Value::has_bool_value() const {
@@ -1191,14 +1329,14 @@ void Value::clear_bool_value() {
clear_has_kind();
}
}
- bool Value::bool_value() const {
+bool Value::bool_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Value.bool_value)
if (has_bool_value()) {
return kind_.bool_value_;
}
return false;
}
- void Value::set_bool_value(bool value) {
+void Value::set_bool_value(bool value) {
if (!has_bool_value()) {
clear_kind();
set_has_bool_value();
@@ -1216,7 +1354,9 @@ void Value::set_has_struct_value() {
}
void Value::clear_struct_value() {
if (has_struct_value()) {
- delete kind_.struct_value_;
+ if (GetArenaNoVirtual() == NULL) {
+ delete kind_.struct_value_;
+ }
clear_has_kind();
}
}
@@ -1230,7 +1370,9 @@ void Value::clear_struct_value() {
if (!has_struct_value()) {
clear_kind();
set_has_struct_value();
- kind_.struct_value_ = new ::google::protobuf::Struct;
+ kind_.struct_value_ =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
return kind_.struct_value_;
@@ -1239,6 +1381,42 @@ void Value::clear_struct_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value)
if (has_struct_value()) {
clear_has_kind();
+ if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Struct* temp = new ::google::protobuf::Struct(*kind_.struct_value_);
+ kind_.struct_value_ = NULL;
+ return temp;
+ } else {
+ ::google::protobuf::Struct* temp = kind_.struct_value_;
+ kind_.struct_value_ = NULL;
+ return temp;
+ }
+ } else {
+ return NULL;
+ }
+}
+void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
+ clear_kind();
+ if (struct_value) {
+ if (GetArenaNoVirtual() != NULL &&
+ ::google::protobuf::Arena::GetArena(struct_value) == NULL) {
+ GetArenaNoVirtual()->Own(struct_value);
+ } else if (GetArenaNoVirtual() !=
+ ::google::protobuf::Arena::GetArena(struct_value)) {
+ ::google::protobuf::Struct* new_struct_value =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
+ GetArenaNoVirtual());
+ new_struct_value->CopyFrom(*struct_value);
+ struct_value = new_struct_value;
+ }
+ set_has_struct_value();
+ kind_.struct_value_ = struct_value;
+ }
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
+}
+ ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value)
+ if (has_struct_value()) {
+ clear_has_kind();
::google::protobuf::Struct* temp = kind_.struct_value_;
kind_.struct_value_ = NULL;
return temp;
@@ -1246,13 +1424,13 @@ void Value::clear_struct_value() {
return NULL;
}
}
-void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
+ void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
clear_kind();
if (struct_value) {
set_has_struct_value();
kind_.struct_value_ = struct_value;
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value)
}
// optional .google.protobuf.ListValue list_value = 6;
@@ -1264,7 +1442,9 @@ void Value::set_has_list_value() {
}
void Value::clear_list_value() {
if (has_list_value()) {
- delete kind_.list_value_;
+ if (GetArenaNoVirtual() == NULL) {
+ delete kind_.list_value_;
+ }
clear_has_kind();
}
}
@@ -1278,7 +1458,9 @@ void Value::clear_list_value() {
if (!has_list_value()) {
clear_kind();
set_has_list_value();
- kind_.list_value_ = new ::google::protobuf::ListValue;
+ kind_.list_value_ =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
return kind_.list_value_;
@@ -1287,6 +1469,42 @@ void Value::clear_list_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.list_value)
if (has_list_value()) {
clear_has_kind();
+ if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::ListValue* temp = new ::google::protobuf::ListValue(*kind_.list_value_);
+ kind_.list_value_ = NULL;
+ return temp;
+ } else {
+ ::google::protobuf::ListValue* temp = kind_.list_value_;
+ kind_.list_value_ = NULL;
+ return temp;
+ }
+ } else {
+ return NULL;
+ }
+}
+void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
+ clear_kind();
+ if (list_value) {
+ if (GetArenaNoVirtual() != NULL &&
+ ::google::protobuf::Arena::GetArena(list_value) == NULL) {
+ GetArenaNoVirtual()->Own(list_value);
+ } else if (GetArenaNoVirtual() !=
+ ::google::protobuf::Arena::GetArena(list_value)) {
+ ::google::protobuf::ListValue* new_list_value =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
+ GetArenaNoVirtual());
+ new_list_value->CopyFrom(*list_value);
+ list_value = new_list_value;
+ }
+ set_has_list_value();
+ kind_.list_value_ = list_value;
+ }
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
+}
+ ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value)
+ if (has_list_value()) {
+ clear_has_kind();
::google::protobuf::ListValue* temp = kind_.list_value_;
kind_.list_value_ = NULL;
return temp;
@@ -1294,13 +1512,13 @@ void Value::clear_list_value() {
return NULL;
}
}
-void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
+ void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::ListValue* list_value) {
clear_kind();
if (list_value) {
set_has_list_value();
kind_.list_value_ = list_value;
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value)
}
bool Value::has_kind() const {
@@ -1312,6 +1530,9 @@ void Value::clear_has_kind() {
Value::KindCase Value::kind_case() const {
return Value::KindCase(_oneof_case_[0]);
}
+inline const Value* Value::internal_default_instance() {
+ return &Value_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1322,24 +1543,34 @@ const int ListValue::kValuesFieldNumber;
ListValue::ListValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.ListValue)
}
+ListValue::ListValue(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ values_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue)
+}
void ListValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
ListValue::ListValue(const ListValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue)
}
void ListValue::SharedCtor() {
- _is_default_instance_ = false;
_cached_size_ = 0;
}
@@ -1349,10 +1580,19 @@ ListValue::~ListValue() {
}
void ListValue::SharedDtor() {
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
}
+
}
+void ListValue::ArenaDtor(void* object) {
+ ListValue* _this = reinterpret_cast< ListValue* >(object);
+ (void)_this;
+}
+void ListValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void ListValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -1364,18 +1604,14 @@ const ::google::protobuf::Descriptor* ListValue::descriptor() {
}
const ListValue& ListValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
+ return *internal_default_instance();
}
-ListValue* ListValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<ListValue> ListValue_default_instance_;
ListValue* ListValue::New(::google::protobuf::Arena* arena) const {
- ListValue* n = new ListValue;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<ListValue>(arena);
}
void ListValue::Clear() {
@@ -1444,6 +1680,7 @@ void ListValue::SerializeWithCachedSizes(
::google::protobuf::uint8* ListValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.ListValue)
// repeated .google.protobuf.Value values = 1;
for (unsigned int i = 0, n = this->values_size(); i < n; i++) {
@@ -1456,30 +1693,32 @@ void ListValue::SerializeWithCachedSizes(
return target;
}
-int ListValue::ByteSize() const {
+size_t ListValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.ListValue)
- int total_size = 0;
+ size_t total_size = 0;
// repeated .google.protobuf.Value values = 1;
- total_size += 1 * this->values_size();
- for (int i = 0; i < this->values_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->values(i));
+ {
+ unsigned int count = this->values_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->values(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void ListValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.ListValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const ListValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const ListValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const ListValue>(
&from);
if (source == NULL) {
@@ -1487,15 +1726,21 @@ void ListValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.ListValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void ListValue::MergeFrom(const ListValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.ListValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void ListValue::UnsafeMergeFrom(const ListValue& from) {
+ GOOGLE_DCHECK(&from != this);
values_.MergeFrom(from.values_);
}
@@ -1510,7 +1755,7 @@ void ListValue::CopyFrom(const ListValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.ListValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool ListValue::IsInitialized() const {
@@ -1520,6 +1765,18 @@ bool ListValue::IsInitialized() const {
void ListValue::Swap(ListValue* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ ListValue temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void ListValue::UnsafeArenaSwap(ListValue* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void ListValue::InternalSwap(ListValue* other) {
@@ -1569,6 +1826,9 @@ ListValue::values() const {
return values_;
}
+inline const ListValue* ListValue::internal_default_instance() {
+ return &ListValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h
index b085b849..ff77bb45 100644
--- a/src/google/protobuf/struct.pb.h
+++ b/src/google/protobuf/struct.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -37,6 +37,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
@@ -78,9 +79,16 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Struct& default_instance();
+ static const Struct* internal_default_instance();
+
+ void UnsafeArenaSwap(Struct* other);
void Swap(Struct* other);
// implements Message ----------------------------------------------
@@ -95,7 +103,7 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -111,6 +119,12 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Struct* other);
+ void UnsafeMergeFrom(const Struct& from);
+ protected:
+ explicit Struct(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -140,7 +154,9 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
typedef ::google::protobuf::internal::MapEntryLite<
::std::string, ::google::protobuf::Value,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
@@ -153,13 +169,15 @@ class LIBPROTOBUF_EXPORT Struct : public ::google::protobuf::Message /* @@protoc
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 > fields_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
void InitAsDefaultInstance();
- static Struct* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Struct> Struct_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Value) */ {
@@ -174,6 +192,10 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Value& default_instance();
@@ -187,6 +209,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
KIND_NOT_SET = 0,
};
+ static const Value* internal_default_instance();
+
+ void UnsafeArenaSwap(Value* other);
void Swap(Value* other);
// implements Message ----------------------------------------------
@@ -201,7 +226,7 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -217,6 +242,12 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Value* other);
+ void UnsafeMergeFrom(const Value& from);
+ protected:
+ explicit Value(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -263,6 +294,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
::std::string* mutable_string_value();
::std::string* release_string_value();
void set_allocated_string_value(::std::string* string_value);
+ ::std::string* unsafe_arena_release_string_value();
+ void unsafe_arena_set_allocated_string_value(
+ ::std::string* string_value);
// optional bool bool_value = 4;
private:
@@ -277,19 +311,37 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
bool has_struct_value() const;
void clear_struct_value();
static const int kStructValueFieldNumber = 5;
+ private:
+ void _slow_mutable_struct_value();
+ void _slow_set_allocated_struct_value(
+ ::google::protobuf::Arena* message_arena, ::google::protobuf::Struct** struct_value);
+ ::google::protobuf::Struct* _slow_release_struct_value();
+ public:
const ::google::protobuf::Struct& struct_value() const;
::google::protobuf::Struct* mutable_struct_value();
::google::protobuf::Struct* release_struct_value();
void set_allocated_struct_value(::google::protobuf::Struct* struct_value);
+ ::google::protobuf::Struct* unsafe_arena_release_struct_value();
+ void unsafe_arena_set_allocated_struct_value(
+ ::google::protobuf::Struct* struct_value);
// optional .google.protobuf.ListValue list_value = 6;
bool has_list_value() const;
void clear_list_value();
static const int kListValueFieldNumber = 6;
+ private:
+ void _slow_mutable_list_value();
+ void _slow_set_allocated_list_value(
+ ::google::protobuf::Arena* message_arena, ::google::protobuf::ListValue** list_value);
+ ::google::protobuf::ListValue* _slow_release_list_value();
+ public:
const ::google::protobuf::ListValue& list_value() const;
::google::protobuf::ListValue* mutable_list_value();
::google::protobuf::ListValue* release_list_value();
void set_allocated_list_value(::google::protobuf::ListValue* list_value);
+ ::google::protobuf::ListValue* unsafe_arena_release_list_value();
+ void unsafe_arena_set_allocated_list_value(
+ ::google::protobuf::ListValue* list_value);
KindCase kind_case() const;
// @@protoc_insertion_point(class_scope:google.protobuf.Value)
@@ -306,7 +358,9 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
inline void clear_has_kind();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
union KindUnion {
KindUnion() {}
int null_value_;
@@ -319,13 +373,15 @@ class LIBPROTOBUF_EXPORT Value : public ::google::protobuf::Message /* @@protoc_
mutable int _cached_size_;
::google::protobuf::uint32 _oneof_case_[1];
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
void InitAsDefaultInstance();
- static Value* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Value> Value_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.ListValue) */ {
@@ -340,9 +396,16 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const ListValue& default_instance();
+ static const ListValue* internal_default_instance();
+
+ void UnsafeArenaSwap(ListValue* other);
void Swap(ListValue* other);
// implements Message ----------------------------------------------
@@ -357,7 +420,7 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -373,6 +436,12 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(ListValue* other);
+ void UnsafeMergeFrom(const ListValue& from);
+ protected:
+ explicit ListValue(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -404,16 +473,20 @@ class LIBPROTOBUF_EXPORT ListValue : public ::google::protobuf::Message /* @@pro
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Value > values_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fstruct_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fstruct_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fstruct_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fstruct_2eproto();
void InitAsDefaultInstance();
- static ListValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<ListValue> ListValue_default_instance_;
+
// ===================================================================
@@ -440,6 +513,9 @@ Struct::mutable_fields() {
return fields_.MutableMap();
}
+inline const Struct* Struct::internal_default_instance() {
+ return &Struct_default_instance_.get();
+}
// -------------------------------------------------------------------
// Value
@@ -511,25 +587,26 @@ inline void Value::set_has_string_value() {
}
inline void Value::clear_string_value() {
if (has_string_value()) {
- kind_.string_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ kind_.string_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
clear_has_kind();
}
}
inline const ::std::string& Value::string_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Value.string_value)
if (has_string_value()) {
- return kind_.string_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return kind_.string_value_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
return *&::google::protobuf::internal::GetEmptyStringAlreadyInited();
}
inline void Value::set_string_value(const ::std::string& value) {
- // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
if (!has_string_value()) {
clear_kind();
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Value.string_value)
}
inline void Value::set_string_value(const char* value) {
@@ -538,18 +615,20 @@ inline void Value::set_string_value(const char* value) {
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(value));
+ kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ ::std::string(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Value.string_value)
}
-inline void Value::set_string_value(const char* value, size_t size) {
+inline void Value::set_string_value(const char* value,
+ size_t size) {
if (!has_string_value()) {
clear_kind();
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- kind_.string_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
- reinterpret_cast<const char*>(value), size));
+ kind_.string_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Value.string_value)
}
inline ::std::string* Value::mutable_string_value() {
@@ -558,14 +637,27 @@ inline ::std::string* Value::mutable_string_value() {
set_has_string_value();
kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
+ return kind_.string_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.string_value)
- return kind_.string_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* Value::release_string_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.string_value)
if (has_string_value()) {
clear_has_kind();
- return kind_.string_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return kind_.string_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+ } else {
+ return NULL;
+ }
+}
+inline ::std::string* Value::unsafe_arena_release_string_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.string_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (has_string_value()) {
+ clear_has_kind();
+ return kind_.string_value_.UnsafeArenaRelease(
+ &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
} else {
return NULL;
}
@@ -577,11 +669,23 @@ inline void Value::set_allocated_string_value(::std::string* string_value) {
clear_kind();
if (string_value != NULL) {
set_has_string_value();
- kind_.string_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- string_value);
+ kind_.string_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value,
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value)
}
+inline void Value::unsafe_arena_set_allocated_string_value(::std::string* string_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (!has_string_value()) {
+ kind_.string_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ clear_kind();
+ if (string_value) {
+ set_has_string_value();
+ kind_.string_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), string_value, GetArenaNoVirtual());
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.string_value)
+}
// optional bool bool_value = 4;
inline bool Value::has_bool_value() const {
@@ -621,7 +725,9 @@ inline void Value::set_has_struct_value() {
}
inline void Value::clear_struct_value() {
if (has_struct_value()) {
- delete kind_.struct_value_;
+ if (GetArenaNoVirtual() == NULL) {
+ delete kind_.struct_value_;
+ }
clear_has_kind();
}
}
@@ -635,7 +741,9 @@ inline ::google::protobuf::Struct* Value::mutable_struct_value() {
if (!has_struct_value()) {
clear_kind();
set_has_struct_value();
- kind_.struct_value_ = new ::google::protobuf::Struct;
+ kind_.struct_value_ =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.struct_value)
return kind_.struct_value_;
@@ -644,6 +752,42 @@ inline ::google::protobuf::Struct* Value::release_struct_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value)
if (has_struct_value()) {
clear_has_kind();
+ if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Struct* temp = new ::google::protobuf::Struct(*kind_.struct_value_);
+ kind_.struct_value_ = NULL;
+ return temp;
+ } else {
+ ::google::protobuf::Struct* temp = kind_.struct_value_;
+ kind_.struct_value_ = NULL;
+ return temp;
+ }
+ } else {
+ return NULL;
+ }
+}
+inline void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
+ clear_kind();
+ if (struct_value) {
+ if (GetArenaNoVirtual() != NULL &&
+ ::google::protobuf::Arena::GetArena(struct_value) == NULL) {
+ GetArenaNoVirtual()->Own(struct_value);
+ } else if (GetArenaNoVirtual() !=
+ ::google::protobuf::Arena::GetArena(struct_value)) {
+ ::google::protobuf::Struct* new_struct_value =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::Struct >(
+ GetArenaNoVirtual());
+ new_struct_value->CopyFrom(*struct_value);
+ struct_value = new_struct_value;
+ }
+ set_has_struct_value();
+ kind_.struct_value_ = struct_value;
+ }
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
+}
+inline ::google::protobuf::Struct* Value::unsafe_arena_release_struct_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value)
+ if (has_struct_value()) {
+ clear_has_kind();
::google::protobuf::Struct* temp = kind_.struct_value_;
kind_.struct_value_ = NULL;
return temp;
@@ -651,13 +795,13 @@ inline ::google::protobuf::Struct* Value::release_struct_value() {
return NULL;
}
}
-inline void Value::set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
+inline void Value::unsafe_arena_set_allocated_struct_value(::google::protobuf::Struct* struct_value) {
clear_kind();
if (struct_value) {
set_has_struct_value();
kind_.struct_value_ = struct_value;
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value)
}
// optional .google.protobuf.ListValue list_value = 6;
@@ -669,7 +813,9 @@ inline void Value::set_has_list_value() {
}
inline void Value::clear_list_value() {
if (has_list_value()) {
- delete kind_.list_value_;
+ if (GetArenaNoVirtual() == NULL) {
+ delete kind_.list_value_;
+ }
clear_has_kind();
}
}
@@ -683,7 +829,9 @@ inline ::google::protobuf::ListValue* Value::mutable_list_value() {
if (!has_list_value()) {
clear_kind();
set_has_list_value();
- kind_.list_value_ = new ::google::protobuf::ListValue;
+ kind_.list_value_ =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
+ GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Value.list_value)
return kind_.list_value_;
@@ -692,6 +840,42 @@ inline ::google::protobuf::ListValue* Value::release_list_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Value.list_value)
if (has_list_value()) {
clear_has_kind();
+ if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::ListValue* temp = new ::google::protobuf::ListValue(*kind_.list_value_);
+ kind_.list_value_ = NULL;
+ return temp;
+ } else {
+ ::google::protobuf::ListValue* temp = kind_.list_value_;
+ kind_.list_value_ = NULL;
+ return temp;
+ }
+ } else {
+ return NULL;
+ }
+}
+inline void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
+ clear_kind();
+ if (list_value) {
+ if (GetArenaNoVirtual() != NULL &&
+ ::google::protobuf::Arena::GetArena(list_value) == NULL) {
+ GetArenaNoVirtual()->Own(list_value);
+ } else if (GetArenaNoVirtual() !=
+ ::google::protobuf::Arena::GetArena(list_value)) {
+ ::google::protobuf::ListValue* new_list_value =
+ ::google::protobuf::Arena::CreateMessage< ::google::protobuf::ListValue >(
+ GetArenaNoVirtual());
+ new_list_value->CopyFrom(*list_value);
+ list_value = new_list_value;
+ }
+ set_has_list_value();
+ kind_.list_value_ = list_value;
+ }
+ // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
+}
+inline ::google::protobuf::ListValue* Value::unsafe_arena_release_list_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value)
+ if (has_list_value()) {
+ clear_has_kind();
::google::protobuf::ListValue* temp = kind_.list_value_;
kind_.list_value_ = NULL;
return temp;
@@ -699,13 +883,13 @@ inline ::google::protobuf::ListValue* Value::release_list_value() {
return NULL;
}
}
-inline void Value::set_allocated_list_value(::google::protobuf::ListValue* list_value) {
+inline void Value::unsafe_arena_set_allocated_list_value(::google::protobuf::ListValue* list_value) {
clear_kind();
if (list_value) {
set_has_list_value();
kind_.list_value_ = list_value;
}
- // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value)
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value)
}
inline bool Value::has_kind() const {
@@ -717,6 +901,9 @@ inline void Value::clear_has_kind() {
inline Value::KindCase Value::kind_case() const {
return Value::KindCase(_oneof_case_[0]);
}
+inline const Value* Value::internal_default_instance() {
+ return &Value_default_instance_.get();
+}
// -------------------------------------------------------------------
// ListValue
@@ -751,6 +938,9 @@ ListValue::values() const {
return values_;
}
+inline const ListValue* ListValue::internal_default_instance() {
+ return &ListValue_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
diff --git a/src/google/protobuf/struct.proto b/src/google/protobuf/struct.proto
index beeba811..7d7808e7 100644
--- a/src/google/protobuf/struct.proto
+++ b/src/google/protobuf/struct.proto
@@ -33,11 +33,11 @@ syntax = "proto3";
package google.protobuf;
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/struct;structpb";
option java_package = "com.google.protobuf";
option java_outer_classname = "StructProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
diff --git a/src/google/protobuf/stubs/atomicops.h b/src/google/protobuf/stubs/atomicops.h
index 9b3d1e6b..10a71ed4 100644
--- a/src/google/protobuf/stubs/atomicops.h
+++ b/src/google/protobuf/stubs/atomicops.h
@@ -196,14 +196,22 @@ Atomic64 Release_Load(volatile const Atomic64* ptr);
// Apple.
#elif defined(GOOGLE_PROTOBUF_OS_APPLE)
+#if __has_feature(cxx_atomic) || _GNUC_VER >= 407
+#include <google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h>
+#else // __has_feature(cxx_atomic) || _GNUC_VER >= 407
#include <google/protobuf/stubs/atomicops_internals_macosx.h>
+#endif // __has_feature(cxx_atomic) || _GNUC_VER >= 407
// GCC.
#elif defined(__GNUC__)
#if defined(GOOGLE_PROTOBUF_ARCH_IA32) || defined(GOOGLE_PROTOBUF_ARCH_X64)
#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)
@@ -213,7 +221,7 @@ Atomic64 Release_Load(volatile const Atomic64* ptr);
#elif defined(GOOGLE_PROTOBUF_ARCH_POWER)
#include <google/protobuf/stubs/atomicops_internals_power.h>
#elif defined(__native_client__)
-#include <google/protobuf/stubs/atomicops_internals_pnacl.h>
+#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))
diff --git a/src/google/protobuf/stubs/atomicops_internals_pnacl.h b/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h
index 3b314fd0..7bc584eb 100644
--- a/src/google/protobuf/stubs/atomicops_internals_pnacl.h
+++ b/src/google/protobuf/stubs/atomicops_internals_generic_c11_atomic.h
@@ -30,8 +30,8 @@
// This file is an internal atomic implementation, use atomicops.h instead.
-#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PNACL_H_
-#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PNACL_H_
+#ifndef GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_
+#define GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_GENERIC_C11_ATOMIC_H_
#include <atomic>
@@ -228,4 +228,4 @@ inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
} // namespace protobuf
} // namespace google
-#endif // GOOGLE_PROTOBUF_ATOMICOPS_INTERNALS_PNACL_H_
+#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
index a0116a60..7f17b30d 100644
--- a/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h
+++ b/src/google/protobuf/stubs/atomicops_internals_generic_gcc.h
@@ -38,7 +38,7 @@ namespace internal {
inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
Atomic32 old_value,
Atomic32 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, true,
+ __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
__ATOMIC_RELAXED, __ATOMIC_RELAXED);
return old_value;
}
@@ -61,7 +61,7 @@ inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
Atomic32 old_value,
Atomic32 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, true,
+ __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
__ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE);
return old_value;
}
@@ -69,7 +69,7 @@ inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
Atomic32 old_value,
Atomic32 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, true,
+ __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
__ATOMIC_RELEASE, __ATOMIC_ACQUIRE);
return old_value;
}
@@ -115,7 +115,7 @@ inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
Atomic64 old_value,
Atomic64 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, true,
+ __atomic_compare_exchange_n(ptr, &old_value, new_value, false,
__ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE);
return old_value;
}
@@ -123,11 +123,29 @@ inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
Atomic64 old_value,
Atomic64 new_value) {
- __atomic_compare_exchange_n(ptr, &old_value, new_value, true,
+ __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
diff --git a/src/google/protobuf/stubs/callback.h b/src/google/protobuf/stubs/callback.h
index 87271c5e..bbd507a8 100644
--- a/src/google/protobuf/stubs/callback.h
+++ b/src/google/protobuf/stubs/callback.h
@@ -381,6 +381,8 @@ class MethodResultCallback_5_2 : public ResultCallback2<R, A1, A2> {
typename remove_reference<P5>::type p5_;
};
+} // namespace internal
+
// See Closure.
inline Closure* NewCallback(void (*function)()) {
return new internal::FunctionClosure0(function, true);
@@ -533,8 +535,6 @@ inline ResultCallback2<R, A1, A2>* NewPermanentCallback(
p2, p3, p4, p5);
}
-} // namespace internal
-
// A function which does nothing. Useful for creating no-op callbacks, e.g.:
// Closure* nothing = NewCallback(&DoNothing);
void LIBPROTOBUF_EXPORT DoNothing();
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h
index 9c05cac3..43e88ff2 100644
--- a/src/google/protobuf/stubs/common.h
+++ b/src/google/protobuf/stubs/common.h
@@ -96,24 +96,24 @@ namespace internal {
// The current version, represented as a single integer to make comparison
// easier: major * 10^6 + minor * 10^3 + micro
-#define GOOGLE_PROTOBUF_VERSION 3000000
+#define GOOGLE_PROTOBUF_VERSION 3001000
// The minimum library version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3000000
+#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 3001000
// The minimum header version which works with the current version of
// the library. This constant should only be used by protoc's C++ code
// generator.
-static const int kMinHeaderVersionForLibrary = 3000000;
+static const int kMinHeaderVersionForLibrary = 3001000;
// The minimum protoc version which works with the current version of the
// headers.
-#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3000000
+#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 3001000
// The minimum header version which works with the current version of
// protoc. This constant should only be used in VerifyVersion().
-static const int kMinHeaderVersionForProtoc = 3000000;
+static const int kMinHeaderVersionForProtoc = 3001000;
// Verifies that the headers and libraries are compatible. Use the macro
// below to call this.
diff --git a/src/google/protobuf/stubs/common_unittest.cc b/src/google/protobuf/stubs/common_unittest.cc
index 25bae9b0..f9e2cfd4 100644
--- a/src/google/protobuf/stubs/common_unittest.cc
+++ b/src/google/protobuf/stubs/common_unittest.cc
@@ -41,8 +41,6 @@
namespace google {
namespace protobuf {
-using internal::NewCallback;
-using internal::NewPermanentCallback;
namespace {
// TODO(kenton): More tests.
diff --git a/src/google/protobuf/stubs/once_unittest.cc b/src/google/protobuf/stubs/once_unittest.cc
index 37def58d..d5f7779e 100644
--- a/src/google/protobuf/stubs/once_unittest.cc
+++ b/src/google/protobuf/stubs/once_unittest.cc
@@ -43,7 +43,6 @@
namespace google {
namespace protobuf {
-using internal::NewCallback;
namespace {
class OnceInitTest : public testing::Test {
@@ -128,11 +127,11 @@ class OnceInitTest : public testing::Test {
};
TestThread* RunInitOnceInNewThread() {
- return new TestThread(internal::NewCallback(this, &OnceInitTest::InitOnce));
+ return new TestThread(NewCallback(this, &OnceInitTest::InitOnce));
}
TestThread* RunInitRecursiveOnceInNewThread() {
return new TestThread(
- internal::NewCallback(this, &OnceInitTest::InitRecursiveOnce));
+ NewCallback(this, &OnceInitTest::InitRecursiveOnce));
}
enum State {
diff --git a/src/google/protobuf/stubs/platform_macros.h b/src/google/protobuf/stubs/platform_macros.h
index 4ba4b348..8b7f224f 100644
--- a/src/google/protobuf/stubs/platform_macros.h
+++ b/src/google/protobuf/stubs/platform_macros.h
@@ -114,11 +114,11 @@ GOOGLE_PROTOBUF_PLATFORM_ERROR
#undef GOOGLE_PROTOBUF_PLATFORM_ERROR
-#if defined(GOOGLE_PROTOBUF_OS_ANDROID) || defined(GOOGLE_PROTOBUF_OS_IPHONE)
+#if defined(GOOGLE_PROTOBUF_OS_ANDROID) || defined(GOOGLE_PROTOBUF_OS_IPHONE) || defined(__OpenBSD__)
// Android ndk does not support the __thread keyword very well yet. Here
// we use pthread_key_create()/pthread_getspecific()/... methods for
// TLS support on android.
-// iOS also does not support the __thread keyword.
+// iOS and OpenBSD also do not support the __thread keyword.
#define GOOGLE_PROTOBUF_NO_THREADLOCAL
#endif
diff --git a/src/google/protobuf/stubs/port.h b/src/google/protobuf/stubs/port.h
index d7f93b4c..376be5f7 100644
--- a/src/google/protobuf/stubs/port.h
+++ b/src/google/protobuf/stubs/port.h
@@ -327,6 +327,61 @@ static inline uint64 bswap_64(uint64 x) {
#endif
// ===================================================================
+// from google3/util/bits/bits.h
+
+class Bits {
+ public:
+ static uint32 Log2FloorNonZero(uint32 n) {
+#if defined(__GNUC__)
+ return 31 ^ __builtin_clz(n);
+#elif defined(COMPILER_MSVC) && defined(_M_IX86)
+ _asm {
+ bsr ebx, n
+ mov n, ebx
+ }
+ return n;
+#else
+ return Log2FloorNonZero_Portable(n);
+#endif
+ }
+
+ static uint64 Log2FloorNonZero64(uint64 n) {
+#if defined(__GNUC__)
+ return 63 ^ __builtin_clzll(n);
+#else
+ return Log2FloorNonZero64_Portable(n);
+#endif
+ }
+ private:
+ static int Log2FloorNonZero_Portable(uint32 n) {
+ if (n == 0)
+ return -1;
+ int log = 0;
+ uint32 value = n;
+ for (int i = 4; i >= 0; --i) {
+ int shift = (1 << i);
+ uint32 x = value >> shift;
+ if (x != 0) {
+ value = x;
+ log += shift;
+ }
+ }
+ assert(value == 1);
+ return log;
+ }
+
+ static int Log2FloorNonZero64_Portable(uint64 n) {
+ const uint32 topbits = static_cast<uint32>(n >> 32);
+ if (topbits == 0) {
+ // Top bits are zero, so scan in bottom bits
+ return Log2FloorNonZero(static_cast<uint32>(n));
+ } else {
+ return 32 + Log2FloorNonZero(topbits);
+ }
+ }
+};
+
+// ===================================================================
// from google3/util/endian/endian.h
LIBPROTOBUF_EXPORT uint32 ghtonl(uint32 x);
diff --git a/src/google/protobuf/stubs/strutil.cc b/src/google/protobuf/stubs/strutil.cc
index 7ba92e8f..4fa8e99f 100644
--- a/src/google/protobuf/stubs/strutil.cc
+++ b/src/google/protobuf/stubs/strutil.cc
@@ -93,6 +93,21 @@ void StripString(string* s, const char* remove, char replacewith) {
}
}
+// ----------------------------------------------------------------------
+// ReplaceCharacters
+// Replaces any occurrence of the character 'remove' (or the characters
+// in 'remove') with the character 'replacewith'.
+// ----------------------------------------------------------------------
+void ReplaceCharacters(string *s, const char *remove, char replacewith) {
+ const char *str_start = s->c_str();
+ const char *str = str_start;
+ for (str = strpbrk(str, remove);
+ str != NULL;
+ str = strpbrk(str + 1, remove)) {
+ (*s)[str - str_start] = replacewith;
+ }
+}
+
void StripWhitespace(string* str) {
int str_length = str->length();
diff --git a/src/google/protobuf/stubs/strutil.h b/src/google/protobuf/stubs/strutil.h
index 8bdd6110..df28c94d 100644
--- a/src/google/protobuf/stubs/strutil.h
+++ b/src/google/protobuf/stubs/strutil.h
@@ -147,7 +147,7 @@ inline string StripSuffixString(const string& str, const string& suffix) {
}
// ----------------------------------------------------------------------
-// StripString
+// ReplaceCharacters
// Replaces any occurrence of the character 'remove' (or the characters
// in 'remove') with the character 'replacewith'.
// Good for keeping html characters or protocol characters (\t) out
@@ -155,6 +155,8 @@ inline string StripSuffixString(const string& str, const string& suffix) {
// StripWhitespace
// Removes whitespaces from both ends of the given string.
// ----------------------------------------------------------------------
+LIBPROTOBUF_EXPORT void ReplaceCharacters(string* s, const char* remove,
+ char replacewith);
LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove,
char replacewith);
diff --git a/src/google/protobuf/stubs/substitute.cc b/src/google/protobuf/stubs/substitute.cc
index c9d95899..7194a5b1 100644
--- a/src/google/protobuf/stubs/substitute.cc
+++ b/src/google/protobuf/stubs/substitute.cc
@@ -113,7 +113,9 @@ void SubstituteAndAppend(
for (int i = 0; format[i] != '\0'; i++) {
if (format[i] == '$') {
if (ascii_isdigit(format[i+1])) {
- const SubstituteArg* src = args_array[format[i+1] - '0'];
+ unsigned int index = format[i+1] - '0';
+ assert(index < 10);
+ const SubstituteArg* src = args_array[index];
memcpy(target, src->data(), src->size());
target += src->size();
++i; // Skip next char.
diff --git a/src/google/protobuf/stubs/type_traits.h b/src/google/protobuf/stubs/type_traits.h
index 0d8127e5..3ab5ea7d 100644
--- a/src/google/protobuf/stubs/type_traits.h
+++ b/src/google/protobuf/stubs/type_traits.h
@@ -139,7 +139,7 @@ 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 { };
-#ifdef HAVE_LONG_LONG
+#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
diff --git a/src/google/protobuf/testing/file.cc b/src/google/protobuf/testing/file.cc
index 3d07b127..470512ed 100644
--- a/src/google/protobuf/testing/file.cc
+++ b/src/google/protobuf/testing/file.cc
@@ -91,6 +91,7 @@ bool File::WriteStringToFile(const string& contents, const string& name) {
if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
GOOGLE_LOG(ERROR) << "fwrite(" << name << "): " << strerror(errno);
+ fclose(file);
return false;
}
@@ -140,12 +141,12 @@ void File::DeleteRecursively(const string& name,
#ifdef _MSC_VER
// This interface is so weird.
- WIN32_FIND_DATA find_data;
- HANDLE find_handle = FindFirstFile((name + "/*").c_str(), &find_data);
+ WIN32_FIND_DATAA find_data;
+ HANDLE find_handle = FindFirstFileA((name + "/*").c_str(), &find_data);
if (find_handle == INVALID_HANDLE_VALUE) {
// Just delete it, whatever it is.
- DeleteFile(name.c_str());
- RemoveDirectory(name.c_str());
+ DeleteFileA(name.c_str());
+ RemoveDirectoryA(name.c_str());
return;
}
@@ -155,15 +156,15 @@ void File::DeleteRecursively(const string& name,
string path = name + "/" + entry_name;
if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
DeleteRecursively(path, NULL, NULL);
- RemoveDirectory(path.c_str());
+ RemoveDirectoryA(path.c_str());
} else {
- DeleteFile(path.c_str());
+ DeleteFileA(path.c_str());
}
}
- } while(FindNextFile(find_handle, &find_data));
+ } while(FindNextFileA(find_handle, &find_data));
FindClose(find_handle);
- RemoveDirectory(name.c_str());
+ RemoveDirectoryA(name.c_str());
#else
// Use opendir()! Yay!
// lstat = Don't follow symbolic links.
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc
index 66b2648b..5192eca9 100644
--- a/src/google/protobuf/text_format.cc
+++ b/src/google/protobuf/text_format.cc
@@ -393,6 +393,16 @@ class TextFormat::Parser::ParserImpl {
DO(ConsumeAnyValue(full_type_name,
message->GetDescriptor()->file()->pool(),
&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() &&
+ reflection->HasField(*message, any_type_url_field)) ||
+ (!any_value_field->is_repeated() &&
+ reflection->HasField(*message, any_value_field))) {
+ ReportError("Non-repeated Any specified multiple times.");
+ return false;
+ }
+ }
reflection->SetString(
message, any_type_url_field,
string(prefix + full_type_name));
@@ -515,18 +525,21 @@ class TextFormat::Parser::ParserImpl {
}
if (field->is_repeated() && TryConsume("[")) {
- // Short repeated format, e.g. "foo: [1, 2, 3]"
- while (true) {
- if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- // Perform special handling for embedded message types.
- DO(ConsumeFieldMessage(message, reflection, field));
- } else {
- DO(ConsumeFieldValue(message, reflection, field));
- }
- if (TryConsume("]")) {
- break;
+ // Short repeated format, e.g. "foo: [1, 2, 3]".
+ if (!TryConsume("]")) {
+ // "foo: []" is treated as empty.
+ while (true) {
+ if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
+ // Perform special handling for embedded message types.
+ DO(ConsumeFieldMessage(message, reflection, field));
+ } else {
+ DO(ConsumeFieldValue(message, reflection, field));
+ }
+ if (TryConsume("]")) {
+ break;
+ }
+ DO(Consume(","));
}
- DO(Consume(","));
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
DO(ConsumeFieldMessage(message, reflection, field));
diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h
index ef3d4a8f..2873d339 100644
--- a/src/google/protobuf/text_format.h
+++ b/src/google/protobuf/text_format.h
@@ -75,6 +75,8 @@ class LIBPROTOBUF_EXPORT TextFormat {
io::ZeroCopyOutputStream* output);
// Like Print(), but outputs directly to a string.
+ // Note: output will be cleared before prior to printing, and will
+ // be left empty even if printing fails.
static bool PrintToString(const Message& message, string* output);
// Like PrintUnknownFields(), but outputs directly to a string.
@@ -301,8 +303,8 @@ class LIBPROTOBUF_EXPORT TextFormat {
int64 truncate_string_field_longer_than_;
google::protobuf::scoped_ptr<const FieldValuePrinter> default_field_value_printer_;
- typedef map<const FieldDescriptor*,
- const FieldValuePrinter*> CustomPrinterMap;
+ typedef std::map<const FieldDescriptor*,
+ const FieldValuePrinter*> CustomPrinterMap;
CustomPrinterMap custom_printers_;
};
@@ -391,11 +393,13 @@ class LIBPROTOBUF_EXPORT TextFormat {
ParseInfoTree* CreateNested(const FieldDescriptor* field);
// Defines the map from the index-th field descriptor to its parse location.
- typedef map<const FieldDescriptor*, vector<ParseLocation> > LocationMap;
+ typedef std::map<const FieldDescriptor*,
+ std::vector<ParseLocation> > LocationMap;
// Defines the map from the index-th field descriptor to the nested parse
// info tree.
- typedef map<const FieldDescriptor*, vector<ParseInfoTree*> > NestedMap;
+ typedef std::map<const FieldDescriptor*,
+ std::vector<ParseInfoTree*> > NestedMap;
LocationMap locations_;
NestedMap nested_;
diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc
index c9521cc3..2f1bd455 100644
--- a/src/google/protobuf/text_format_unittest.cc
+++ b/src/google/protobuf/text_format_unittest.cc
@@ -157,7 +157,21 @@ TEST_F(TextFormatTest, ShortPrimitiveRepeateds) {
TextFormat::Printer printer;
printer.SetUseShortRepeatedPrimitives(true);
string text;
- printer.PrintToString(proto_, &text);
+ EXPECT_TRUE(printer.PrintToString(proto_, &text));
+
+ EXPECT_EQ("optional_int32: 123\n"
+ "repeated_int32: [456, 789]\n"
+ "repeated_string: \"foo\"\n"
+ "repeated_string: \"bar\"\n"
+ "repeated_nested_message {\n bb: 2\n}\n"
+ "repeated_nested_message {\n bb: 3\n}\n"
+ "repeated_nested_enum: [FOO, BAR]\n",
+ text);
+
+ // Verify that any existing data in the string is cleared when
+ // PrintToString() is called.
+ text = "just some data here...\n\nblah blah";
+ EXPECT_TRUE(printer.PrintToString(proto_, &text));
EXPECT_EQ("optional_int32: 123\n"
"repeated_int32: [456, 789]\n"
@@ -170,7 +184,7 @@ TEST_F(TextFormatTest, ShortPrimitiveRepeateds) {
// Try in single-line mode.
printer.SetSingleLineMode(true);
- printer.PrintToString(proto_, &text);
+ EXPECT_TRUE(printer.PrintToString(proto_, &text));
EXPECT_EQ("optional_int32: 123 "
"repeated_int32: [456, 789] "
@@ -659,6 +673,87 @@ TEST_F(TextFormatTest, ParseShortRepeatedForm) {
EXPECT_EQ(4, proto_.repeatedgroup(1).a());
}
+TEST_F(TextFormatTest, ParseShortRepeatedWithTrailingComma) {
+ string parse_string = "repeated_int32: [456,]\n";
+ ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
+ parse_string = "repeated_nested_enum: [ FOO , ]";
+ ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
+ parse_string = "repeated_string: [ \"foo\", ]";
+ ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
+ parse_string = "repeated_nested_message: [ { bb: 1 }, ]";
+ ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
+ parse_string = "RepeatedGroup [{ a: 3 },]\n";
+}
+
+TEST_F(TextFormatTest, ParseShortRepeatedEmpty) {
+ string parse_string =
+ "repeated_int32: []\n"
+ "repeated_nested_enum: []\n"
+ "repeated_string: []\n"
+ "repeated_nested_message: []\n"
+ "RepeatedGroup []\n";
+
+ ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
+
+ EXPECT_EQ(0, proto_.repeated_int32_size());
+ EXPECT_EQ(0, proto_.repeated_nested_enum_size());
+ EXPECT_EQ(0, proto_.repeated_string_size());
+ EXPECT_EQ(0, proto_.repeated_nested_message_size());
+ EXPECT_EQ(0, proto_.repeatedgroup_size());
+}
+
+TEST_F(TextFormatTest, ParseShortRepeatedConcatenatedWithEmpty) {
+ string parse_string =
+ // Starting with empty [] should have no impact.
+ "repeated_int32: []\n"
+ "repeated_nested_enum: []\n"
+ "repeated_string: []\n"
+ "repeated_nested_message: []\n"
+ "RepeatedGroup []\n"
+ // Mixed short-form and long-form are simply concatenated.
+ "repeated_int32: 1\n"
+ "repeated_int32: [456, 789]\n"
+ "repeated_nested_enum: [ FOO ,BAR, # comment\n"
+ " 3]\n"
+ // Note that while the printer won't print repeated strings in short-form,
+ // the parser will accept them.
+ "repeated_string: [ \"foo\", 'bar' ]\n"
+ // Repeated message
+ "repeated_nested_message: [ { bb: 1 }, { bb : 2 }]\n"
+ // Repeated group
+ "RepeatedGroup [{ a: 3 },{ a: 4 }]\n"
+ // Adding empty [] should have no impact.
+ "repeated_int32: []\n"
+ "repeated_nested_enum: []\n"
+ "repeated_string: []\n"
+ "repeated_nested_message: []\n"
+ "RepeatedGroup []\n";
+
+ ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
+
+ ASSERT_EQ(3, proto_.repeated_int32_size());
+ EXPECT_EQ(1, proto_.repeated_int32(0));
+ EXPECT_EQ(456, proto_.repeated_int32(1));
+ EXPECT_EQ(789, proto_.repeated_int32(2));
+
+ ASSERT_EQ(3, proto_.repeated_nested_enum_size());
+ EXPECT_EQ(unittest::TestAllTypes::FOO, proto_.repeated_nested_enum(0));
+ EXPECT_EQ(unittest::TestAllTypes::BAR, proto_.repeated_nested_enum(1));
+ EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.repeated_nested_enum(2));
+
+ ASSERT_EQ(2, proto_.repeated_string_size());
+ EXPECT_EQ("foo", proto_.repeated_string(0));
+ EXPECT_EQ("bar", proto_.repeated_string(1));
+
+ ASSERT_EQ(2, proto_.repeated_nested_message_size());
+ EXPECT_EQ(1, proto_.repeated_nested_message(0).bb());
+ EXPECT_EQ(2, proto_.repeated_nested_message(1).bb());
+
+ ASSERT_EQ(2, proto_.repeatedgroup_size());
+ EXPECT_EQ(3, proto_.repeatedgroup(0).a());
+ EXPECT_EQ(4, proto_.repeatedgroup(1).a());
+}
+
TEST_F(TextFormatTest, Comments) {
// Test that comments are ignored.
diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc
index 542e5ed7..b4258ae4 100644
--- a/src/google/protobuf/timestamp.pb.cc
+++ b/src/google/protobuf/timestamp.pb.cc
@@ -44,20 +44,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2ftimestamp_2eproto() {
Timestamp_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Timestamp_descriptor_,
- Timestamp::default_instance_,
+ Timestamp::internal_default_instance(),
Timestamp_offsets_,
-1,
-1,
-1,
sizeof(Timestamp),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Timestamp, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Timestamp, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Timestamp, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2ftimestamp_2eproto);
}
@@ -66,37 +65,49 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Timestamp_descriptor_, &Timestamp::default_instance());
+ Timestamp_descriptor_, Timestamp::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto() {
- delete Timestamp::default_instance_;
+ Timestamp_default_instance_.Shutdown();
delete Timestamp_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ Timestamp_default_instance_.DefaultConstruct();
+ Timestamp_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\037google/protobuf/timestamp.proto\022\017googl"
"e.protobuf\"+\n\tTimestamp\022\017\n\007seconds\030\001 \001(\003"
- "\022\r\n\005nanos\030\002 \001(\005B\201\001\n\023com.google.protobufB"
- "\016TimestampProtoP\001Z+github.com/golang/pro"
- "tobuf/ptypes/timestamp\240\001\001\370\001\001\242\002\003GPB\252\002\036Goo"
- "gle.Protobuf.WellKnownTypesb\006proto3", 235);
+ "\022\r\n\005nanos\030\002 \001(\005B~\n\023com.google.protobufB\016"
+ "TimestampProtoP\001Z+github.com/golang/prot"
+ "obuf/ptypes/timestamp\370\001\001\242\002\003GPB\252\002\036Google."
+ "Protobuf.WellKnownTypesb\006proto3", 231);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/timestamp.proto", &protobuf_RegisterTypes);
- Timestamp::default_instance_ = new Timestamp();
- Timestamp::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2ftimestamp_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2ftimestamp_2eproto() {
@@ -104,6 +115,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2ftimestamp_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2ftimestamp_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -113,35 +134,36 @@ const int Timestamp::kNanosFieldNumber;
Timestamp::Timestamp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Timestamp)
}
-
Timestamp::Timestamp(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp)
}
void Timestamp::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Timestamp::Timestamp(const Timestamp& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Timestamp)
}
void Timestamp::SharedCtor() {
- _is_default_instance_ = false;
+ ::memset(&seconds_, 0, reinterpret_cast<char*>(&nanos_) -
+ reinterpret_cast<char*>(&seconds_) + sizeof(nanos_));
_cached_size_ = 0;
- seconds_ = GOOGLE_LONGLONG(0);
- nanos_ = 0;
}
Timestamp::~Timestamp() {
@@ -150,12 +172,11 @@ Timestamp::~Timestamp() {
}
void Timestamp::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void Timestamp::ArenaDtor(void* object) {
@@ -175,11 +196,11 @@ const ::google::protobuf::Descriptor* Timestamp::descriptor() {
}
const Timestamp& Timestamp::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
+ return *internal_default_instance();
}
-Timestamp* Timestamp::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Timestamp> Timestamp_default_instance_;
Timestamp* Timestamp::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<Timestamp>(arena);
@@ -199,7 +220,7 @@ void Timestamp::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
@@ -223,10 +244,10 @@ bool Timestamp::MergePartialFromCodedStream(
// optional int64 seconds = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &seconds_)));
-
} else {
goto handle_unusual;
}
@@ -238,10 +259,10 @@ bool Timestamp::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_nanos:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &nanos_)));
-
} else {
goto handle_unusual;
}
@@ -288,6 +309,7 @@ void Timestamp::SerializeWithCachedSizes(
::google::protobuf::uint8* Timestamp::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Timestamp)
// optional int64 seconds = 1;
if (this->seconds() != 0) {
@@ -303,9 +325,9 @@ void Timestamp::SerializeWithCachedSizes(
return target;
}
-int Timestamp::ByteSize() const {
+size_t Timestamp::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Timestamp)
- int total_size = 0;
+ size_t total_size = 0;
// optional int64 seconds = 1;
if (this->seconds() != 0) {
@@ -321,18 +343,17 @@ int Timestamp::ByteSize() const {
this->nanos());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Timestamp::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Timestamp)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Timestamp* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Timestamp* source =
::google::protobuf::internal::DynamicCastToGenerated<const Timestamp>(
&from);
if (source == NULL) {
@@ -340,15 +361,21 @@ void Timestamp::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Timestamp)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Timestamp::MergeFrom(const Timestamp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Timestamp)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Timestamp::UnsafeMergeFrom(const Timestamp& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.seconds() != 0) {
set_seconds(from.seconds());
}
@@ -368,7 +395,7 @@ void Timestamp::CopyFrom(const Timestamp& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Timestamp)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Timestamp::IsInitialized() const {
@@ -382,7 +409,7 @@ void Timestamp::Swap(Timestamp* other) {
InternalSwap(other);
} else {
Timestamp temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -414,11 +441,11 @@ void Timestamp::InternalSwap(Timestamp* other) {
void Timestamp::clear_seconds() {
seconds_ = GOOGLE_LONGLONG(0);
}
- ::google::protobuf::int64 Timestamp::seconds() const {
+::google::protobuf::int64 Timestamp::seconds() const {
// @@protoc_insertion_point(field_get:google.protobuf.Timestamp.seconds)
return seconds_;
}
- void Timestamp::set_seconds(::google::protobuf::int64 value) {
+void Timestamp::set_seconds(::google::protobuf::int64 value) {
seconds_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Timestamp.seconds)
@@ -428,16 +455,19 @@ void Timestamp::clear_seconds() {
void Timestamp::clear_nanos() {
nanos_ = 0;
}
- ::google::protobuf::int32 Timestamp::nanos() const {
+::google::protobuf::int32 Timestamp::nanos() const {
// @@protoc_insertion_point(field_get:google.protobuf.Timestamp.nanos)
return nanos_;
}
- void Timestamp::set_nanos(::google::protobuf::int32 value) {
+void Timestamp::set_nanos(::google::protobuf::int32 value) {
nanos_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Timestamp.nanos)
}
+inline const Timestamp* Timestamp::internal_default_instance() {
+ return &Timestamp_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h
index 19f4f86f..1abe8d0c 100644
--- a/src/google/protobuf/timestamp.pb.h
+++ b/src/google/protobuf/timestamp.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -34,6 +34,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2ftimestamp_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto();
@@ -60,6 +61,8 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const Timestamp& default_instance();
+ static const Timestamp* internal_default_instance();
+
void UnsafeArenaSwap(Timestamp* other);
void Swap(Timestamp* other);
@@ -75,7 +78,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -91,6 +94,7 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Timestamp* other);
+ void UnsafeMergeFrom(const Timestamp& from);
protected:
explicit Timestamp(::google::protobuf::Arena* arena);
private:
@@ -130,17 +134,18 @@ class LIBPROTOBUF_EXPORT Timestamp : public ::google::protobuf::Message /* @@pro
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::int64 seconds_;
::google::protobuf::int32 nanos_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftimestamp_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftimestamp_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ftimestamp_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ftimestamp_2eproto();
void InitAsDefaultInstance();
- static Timestamp* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Timestamp> Timestamp_default_instance_;
+
// ===================================================================
@@ -177,6 +182,9 @@ inline void Timestamp::set_nanos(::google::protobuf::int32 value) {
// @@protoc_insertion_point(field_set:google.protobuf.Timestamp.nanos)
}
+inline const Timestamp* Timestamp::internal_default_instance() {
+ return &Timestamp_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/timestamp.proto b/src/google/protobuf/timestamp.proto
index 7992a858..67e2eba4 100644
--- a/src/google/protobuf/timestamp.proto
+++ b/src/google/protobuf/timestamp.proto
@@ -38,7 +38,6 @@ option go_package = "github.com/golang/protobuf/ptypes/timestamp";
option java_package = "com.google.protobuf";
option java_outer_classname = "TimestampProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// A Timestamp represents a point in time independent of any time zone
@@ -90,16 +89,14 @@ option objc_class_prefix = "GPB";
//
// Example 5: Compute Timestamp from current time in Python.
//
-// now = time.time()
-// seconds = int(now)
-// nanos = int((now - seconds) * 10**9)
-// timestamp = Timestamp(seconds=seconds, nanos=nanos)
+// timestamp = Timestamp()
+// timestamp.GetCurrentTime()
//
//
message Timestamp {
// Represents seconds of UTC time since Unix epoch
- // 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
int64 seconds = 1;
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc
index 7ba909ef..cc80dd92 100644
--- a/src/google/protobuf/type.pb.cc
+++ b/src/google/protobuf/type.pb.cc
@@ -63,14 +63,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto() {
Type_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Type_descriptor_,
- Type::default_instance_,
+ Type::internal_default_instance(),
Type_offsets_,
-1,
-1,
-1,
sizeof(Type),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Type, _internal_metadata_));
Field_descriptor_ = file->message_type(1);
static const int Field_offsets_[10] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, kind_),
@@ -87,14 +86,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto() {
Field_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Field_descriptor_,
- Field::default_instance_,
+ Field::internal_default_instance(),
Field_offsets_,
-1,
-1,
-1,
sizeof(Field),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Field, _internal_metadata_));
Field_Kind_descriptor_ = Field_descriptor_->enum_type(0);
Field_Cardinality_descriptor_ = Field_descriptor_->enum_type(1);
Enum_descriptor_ = file->message_type(2);
@@ -108,14 +106,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto() {
Enum_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Enum_descriptor_,
- Enum::default_instance_,
+ Enum::internal_default_instance(),
Enum_offsets_,
-1,
-1,
-1,
sizeof(Enum),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Enum, _internal_metadata_));
EnumValue_descriptor_ = file->message_type(3);
static const int EnumValue_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, name_),
@@ -125,14 +122,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto() {
EnumValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
EnumValue_descriptor_,
- EnumValue::default_instance_,
+ EnumValue::internal_default_instance(),
EnumValue_offsets_,
-1,
-1,
-1,
sizeof(EnumValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValue, _internal_metadata_));
Option_descriptor_ = file->message_type(4);
static const int Option_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, name_),
@@ -141,21 +137,20 @@ void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto() {
Option_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Option_descriptor_,
- Option::default_instance_,
+ Option::internal_default_instance(),
Option_offsets_,
-1,
-1,
-1,
sizeof(Option),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Option, _internal_metadata_));
Syntax_descriptor_ = file->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto);
}
@@ -164,41 +159,63 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Type_descriptor_, &Type::default_instance());
+ Type_descriptor_, Type::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Field_descriptor_, &Field::default_instance());
+ Field_descriptor_, Field::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Enum_descriptor_, &Enum::default_instance());
+ Enum_descriptor_, Enum::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- EnumValue_descriptor_, &EnumValue::default_instance());
+ EnumValue_descriptor_, EnumValue::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Option_descriptor_, &Option::default_instance());
+ Option_descriptor_, Option::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto() {
- delete Type::default_instance_;
+ Type_default_instance_.Shutdown();
delete Type_reflection_;
- delete Field::default_instance_;
+ Field_default_instance_.Shutdown();
delete Field_reflection_;
- delete Enum::default_instance_;
+ Enum_default_instance_.Shutdown();
delete Enum_reflection_;
- delete EnumValue::default_instance_;
+ EnumValue_default_instance_.Shutdown();
delete EnumValue_reflection_;
- delete Option::default_instance_;
+ Option_default_instance_.Shutdown();
delete Option_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
- ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
+ ::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fsource_5fcontext_2eproto();
+ ::google::protobuf::internal::GetEmptyString();
+ Type_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ Field_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ Enum_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ EnumValue_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ Option_default_instance_.DefaultConstruct();
+ Type_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Field_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Enum_default_instance_.get_mutable()->InitAsDefaultInstance();
+ EnumValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Option_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\032google/protobuf/type.proto\022\017google.pro"
"tobuf\032\031google/protobuf/any.proto\032$google"
@@ -237,23 +254,20 @@ void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto() {
"\022\014\n\004name\030\001 \001(\t\022#\n\005value\030\002 \001(\0132\024.google.p"
"rotobuf.Any*.\n\006Syntax\022\021\n\rSYNTAX_PROTO2\020\000"
"\022\021\n\rSYNTAX_PROTO3\020\001BL\n\023com.google.protob"
- "ufB\tTypeProtoP\001\240\001\001\242\002\003GPB\252\002\036Google.Protob"
+ "ufB\tTypeProtoP\001\370\001\001\242\002\003GPB\252\002\036Google.Protob"
"uf.WellKnownTypesb\006proto3", 1545);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/type.proto", &protobuf_RegisterTypes);
- Type::default_instance_ = new Type();
- Field::default_instance_ = new Field();
- Enum::default_instance_ = new Enum();
- EnumValue::default_instance_ = new EnumValue();
- Option::default_instance_ = new Option();
- Type::default_instance_->InitAsDefaultInstance();
- Field::default_instance_->InitAsDefaultInstance();
- Enum::default_instance_->InitAsDefaultInstance();
- EnumValue::default_instance_->InitAsDefaultInstance();
- Option::default_instance_->InitAsDefaultInstance();
+ ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
+ ::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fsource_5fcontext_2eproto();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2ftype_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2ftype_2eproto() {
@@ -265,7 +279,7 @@ const ::google::protobuf::EnumDescriptor* Syntax_descriptor() {
return Syntax_descriptor_;
}
bool Syntax_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 0:
case 1:
return true;
@@ -275,8 +289,51 @@ bool Syntax_IsValid(int value) {
}
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
+void Type::_slow_mutable_source_context() {
+ source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
+ GetArenaNoVirtual());
+}
+::google::protobuf::SourceContext* Type::_slow_release_source_context() {
+ if (source_context_ == NULL) {
+ return NULL;
+ } else {
+ ::google::protobuf::SourceContext* temp = new ::google::protobuf::SourceContext(*source_context_);
+ source_context_ = NULL;
+ return temp;
+ }
+}
+::google::protobuf::SourceContext* Type::unsafe_arena_release_source_context() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
+}
+void Type::unsafe_arena_set_allocated_source_context(
+ ::google::protobuf::SourceContext* source_context) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete source_context_;
+ }
+ source_context_ = source_context;
+ if (source_context) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.source_context)
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Type::kNameFieldNumber;
const int Type::kFieldsFieldNumber;
@@ -288,30 +345,42 @@ const int Type::kSyntaxFieldNumber;
Type::Type()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Type)
}
+Type::Type(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ fields_(arena),
+ oneofs_(arena),
+ options_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Type)
+}
void Type::InitAsDefaultInstance() {
- _is_default_instance_ = true;
- source_context_ = const_cast< ::google::protobuf::SourceContext*>(&::google::protobuf::SourceContext::default_instance());
+ source_context_ = const_cast< ::google::protobuf::SourceContext*>(
+ ::google::protobuf::SourceContext::internal_default_instance());
}
Type::Type(const Type& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Type)
}
void Type::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
source_context_ = NULL;
syntax_ = 0;
+ _cached_size_ = 0;
}
Type::~Type() {
@@ -320,12 +389,23 @@ Type::~Type() {
}
void Type::SharedDtor() {
- name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
+ }
+
+ name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ if (this != &Type_default_instance_.get()) {
delete source_context_;
}
}
+void Type::ArenaDtor(void* object) {
+ Type* _this = reinterpret_cast< Type* >(object);
+ (void)_this;
+}
+void Type::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Type::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -337,23 +417,19 @@ const ::google::protobuf::Descriptor* Type::descriptor() {
}
const Type& Type::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ return *internal_default_instance();
}
-Type* Type::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Type> Type_default_instance_;
Type* Type::New(::google::protobuf::Arena* arena) const {
- Type* n = new Type;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Type>(arena);
}
void Type::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Type)
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
source_context_ = NULL;
syntax_ = 0;
@@ -543,6 +619,7 @@ void Type::SerializeWithCachedSizes(
::google::protobuf::uint8* Type::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Type)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -596,9 +673,9 @@ void Type::SerializeWithCachedSizes(
return target;
}
-int Type::ByteSize() const {
+size_t Type::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Type)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -621,40 +698,46 @@ int Type::ByteSize() const {
}
// repeated .google.protobuf.Field fields = 2;
- total_size += 1 * this->fields_size();
- for (int i = 0; i < this->fields_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->fields(i));
+ {
+ unsigned int count = this->fields_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->fields(i));
+ }
}
// repeated string oneofs = 3;
- total_size += 1 * this->oneofs_size();
+ total_size += 1 *
+ ::google::protobuf::internal::FromIntSize(this->oneofs_size());
for (int i = 0; i < this->oneofs_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->oneofs(i));
}
// repeated .google.protobuf.Option options = 4;
- total_size += 1 * this->options_size();
- for (int i = 0; i < this->options_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ {
+ unsigned int count = this->options_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->options(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Type::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Type)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Type* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Type* source =
::google::protobuf::internal::DynamicCastToGenerated<const Type>(
&from);
if (source == NULL) {
@@ -662,21 +745,26 @@ void Type::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Type)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Type::MergeFrom(const Type& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Type)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Type::UnsafeMergeFrom(const Type& from) {
+ GOOGLE_DCHECK(&from != this);
fields_.MergeFrom(from.fields_);
- oneofs_.MergeFrom(from.oneofs_);
+ oneofs_.UnsafeMergeFrom(from.oneofs_);
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ set_name(from.name());
}
if (from.has_source_context()) {
mutable_source_context()->::google::protobuf::SourceContext::MergeFrom(from.source_context());
@@ -697,7 +785,7 @@ void Type::CopyFrom(const Type& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Type)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Type::IsInitialized() const {
@@ -707,6 +795,18 @@ bool Type::IsInitialized() const {
void Type::Swap(Type* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Type temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Type::UnsafeArenaSwap(Type* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Type::InternalSwap(Type* other) {
@@ -733,47 +833,69 @@ void Type::InternalSwap(Type* other) {
// optional string name = 1;
void Type::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Type::name() const {
+const ::std::string& Type::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Type::set_name(const ::std::string& value) {
+void Type::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Type.name)
}
- void Type::set_name(const char* value) {
+void Type::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Type.name)
}
- void Type::set_name(const char* value, size_t size) {
+void Type::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.name)
}
- ::std::string* Type::mutable_name() {
+::std::string* Type::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Type::release_name() {
+::std::string* Type::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Type.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- void Type::set_allocated_name(::std::string* name) {
+::std::string* Type::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+void Type::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.name)
}
+void Type::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.name)
+}
// repeated .google.protobuf.Field fields = 2;
int Type::fields_size() const {
@@ -812,49 +934,49 @@ int Type::oneofs_size() const {
void Type::clear_oneofs() {
oneofs_.Clear();
}
- const ::std::string& Type::oneofs(int index) const {
+const ::std::string& Type::oneofs(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.oneofs)
return oneofs_.Get(index);
}
- ::std::string* Type::mutable_oneofs(int index) {
+::std::string* Type::mutable_oneofs(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.oneofs)
return oneofs_.Mutable(index);
}
- void Type::set_oneofs(int index, const ::std::string& value) {
+void Type::set_oneofs(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:google.protobuf.Type.oneofs)
oneofs_.Mutable(index)->assign(value);
}
- void Type::set_oneofs(int index, const char* value) {
+void Type::set_oneofs(int index, const char* value) {
oneofs_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:google.protobuf.Type.oneofs)
}
- void Type::set_oneofs(int index, const char* value, size_t size) {
+void Type::set_oneofs(int index, const char* value, size_t size) {
oneofs_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.oneofs)
}
- ::std::string* Type::add_oneofs() {
+::std::string* Type::add_oneofs() {
// @@protoc_insertion_point(field_add_mutable:google.protobuf.Type.oneofs)
return oneofs_.Add();
}
- void Type::add_oneofs(const ::std::string& value) {
+void Type::add_oneofs(const ::std::string& value) {
oneofs_.Add()->assign(value);
// @@protoc_insertion_point(field_add:google.protobuf.Type.oneofs)
}
- void Type::add_oneofs(const char* value) {
+void Type::add_oneofs(const char* value) {
oneofs_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:google.protobuf.Type.oneofs)
}
- void Type::add_oneofs(const char* value, size_t size) {
+void Type::add_oneofs(const char* value, size_t size) {
oneofs_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:google.protobuf.Type.oneofs)
}
- const ::google::protobuf::RepeatedPtrField< ::std::string>&
+const ::google::protobuf::RepeatedPtrField< ::std::string>&
Type::oneofs() const {
// @@protoc_insertion_point(field_list:google.protobuf.Type.oneofs)
return oneofs_;
}
- ::google::protobuf::RepeatedPtrField< ::std::string>*
+::google::protobuf::RepeatedPtrField< ::std::string>*
Type::mutable_oneofs() {
// @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.oneofs)
return &oneofs_;
@@ -892,7 +1014,7 @@ Type::options() const {
// optional .google.protobuf.SourceContext source_context = 5;
bool Type::has_source_context() const {
- return !_is_default_instance_ && source_context_ != NULL;
+ return this != internal_default_instance() && source_context_ != NULL;
}
void Type::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
@@ -900,12 +1022,13 @@ void Type::clear_source_context() {
}
const ::google::protobuf::SourceContext& Type::source_context() const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.source_context)
- return source_context_ != NULL ? *source_context_ : *default_instance_->source_context_;
+ return source_context_ != NULL ? *source_context_
+ : *::google::protobuf::SourceContext::internal_default_instance();
}
::google::protobuf::SourceContext* Type::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = new ::google::protobuf::SourceContext;
+ _slow_mutable_source_context();
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context)
return source_context_;
@@ -913,12 +1036,24 @@ const ::google::protobuf::SourceContext& Type::source_context() const {
::google::protobuf::SourceContext* Type::release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Type.source_context)
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ return _slow_release_source_context();
+ } else {
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
+ }
}
-void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- delete source_context_;
+ void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete source_context_;
+ }
+ if (source_context != NULL) {
+ if (message_arena != NULL) {
+ message_arena->Own(source_context);
+ }
+ }
source_context_ = source_context;
if (source_context) {
@@ -932,16 +1067,19 @@ void Type::set_allocated_source_context(::google::protobuf::SourceContext* sourc
void Type::clear_syntax() {
syntax_ = 0;
}
- ::google::protobuf::Syntax Type::syntax() const {
+::google::protobuf::Syntax Type::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.syntax)
return static_cast< ::google::protobuf::Syntax >(syntax_);
}
- void Type::set_syntax(::google::protobuf::Syntax value) {
+void Type::set_syntax(::google::protobuf::Syntax value) {
syntax_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Type.syntax)
}
+inline const Type* Type::internal_default_instance() {
+ return &Type_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -951,7 +1089,7 @@ const ::google::protobuf::EnumDescriptor* Field_Kind_descriptor() {
return Field_Kind_descriptor_;
}
bool Field_Kind_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 0:
case 1:
case 2:
@@ -1006,7 +1144,7 @@ const ::google::protobuf::EnumDescriptor* Field_Cardinality_descriptor() {
return Field_Cardinality_descriptor_;
}
bool Field_Cardinality_IsValid(int value) {
- switch(value) {
+ switch (value) {
case 0:
case 1:
case 2:
@@ -1041,35 +1179,41 @@ const int Field::kDefaultValueFieldNumber;
Field::Field()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Field)
}
+Field::Field(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ options_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Field)
+}
void Field::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Field::Field(const Field& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Field)
}
void Field::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
- kind_ = 0;
- cardinality_ = 0;
- number_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- oneof_index_ = 0;
- packed_ = false;
json_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
default_value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ::memset(&kind_, 0, reinterpret_cast<char*>(&packed_) -
+ reinterpret_cast<char*>(&kind_) + sizeof(packed_));
+ _cached_size_ = 0;
}
Field::~Field() {
@@ -1078,14 +1222,23 @@ Field::~Field() {
}
void Field::SharedDtor() {
- name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- json_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- default_value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
}
+
+ name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ type_url_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ json_name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ default_value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
}
+void Field::ArenaDtor(void* object) {
+ Field* _this = reinterpret_cast< Field* >(object);
+ (void)_this;
+}
+void Field::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Field::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -1097,18 +1250,14 @@ const ::google::protobuf::Descriptor* Field::descriptor() {
}
const Field& Field::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ return *internal_default_instance();
}
-Field* Field::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Field> Field_default_instance_;
Field* Field::New(::google::protobuf::Arena* arena) const {
- Field* n = new Field;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Field>(arena);
}
void Field::Clear() {
@@ -1125,17 +1274,15 @@ void Field::Clear() {
#endif
#define ZR_(first, last) do {\
- ::memset(&first, 0,\
+ ::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
- ZR_(kind_, cardinality_);
- ZR_(number_, oneof_index_);
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- packed_ = false;
- json_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ZR_(kind_, packed_);
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ type_url_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+ default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
#undef ZR_HELPER_
#undef ZR_
@@ -1188,10 +1335,10 @@ bool Field::MergePartialFromCodedStream(
case 3: {
if (tag == 24) {
parse_number:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &number_)));
-
} else {
goto handle_unusual;
}
@@ -1237,10 +1384,10 @@ bool Field::MergePartialFromCodedStream(
case 7: {
if (tag == 56) {
parse_oneof_index:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &oneof_index_)));
-
} else {
goto handle_unusual;
}
@@ -1252,10 +1399,10 @@ bool Field::MergePartialFromCodedStream(
case 8: {
if (tag == 64) {
parse_packed:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &packed_)));
-
} else {
goto handle_unusual;
}
@@ -1416,6 +1563,7 @@ void Field::SerializeWithCachedSizes(
::google::protobuf::uint8* Field::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Field)
// optional .google.protobuf.Field.Kind kind = 1;
if (this->kind() != 0) {
@@ -1499,9 +1647,9 @@ void Field::SerializeWithCachedSizes(
return target;
}
-int Field::ByteSize() const {
+size_t Field::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Field)
- int total_size = 0;
+ size_t total_size = 0;
// optional .google.protobuf.Field.Kind kind = 1;
if (this->kind() != 0) {
@@ -1563,25 +1711,27 @@ int Field::ByteSize() const {
}
// repeated .google.protobuf.Option options = 9;
- total_size += 1 * this->options_size();
- for (int i = 0; i < this->options_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ {
+ unsigned int count = this->options_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->options(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Field::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Field)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Field* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Field* source =
::google::protobuf::internal::DynamicCastToGenerated<const Field>(
&from);
if (source == NULL) {
@@ -1589,15 +1739,21 @@ void Field::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Field)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Field::MergeFrom(const Field& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Field)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Field::UnsafeMergeFrom(const Field& from) {
+ GOOGLE_DCHECK(&from != this);
options_.MergeFrom(from.options_);
if (from.kind() != 0) {
set_kind(from.kind());
@@ -1609,12 +1765,10 @@ void Field::MergeFrom(const Field& from) {
set_number(from.number());
}
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ set_name(from.name());
}
if (from.type_url().size() > 0) {
-
- type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_);
+ set_type_url(from.type_url());
}
if (from.oneof_index() != 0) {
set_oneof_index(from.oneof_index());
@@ -1623,12 +1777,10 @@ void Field::MergeFrom(const Field& from) {
set_packed(from.packed());
}
if (from.json_name().size() > 0) {
-
- json_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.json_name_);
+ set_json_name(from.json_name());
}
if (from.default_value().size() > 0) {
-
- default_value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.default_value_);
+ set_default_value(from.default_value());
}
}
@@ -1643,7 +1795,7 @@ void Field::CopyFrom(const Field& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Field)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Field::IsInitialized() const {
@@ -1653,6 +1805,18 @@ bool Field::IsInitialized() const {
void Field::Swap(Field* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Field temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Field::UnsafeArenaSwap(Field* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Field::InternalSwap(Field* other) {
@@ -1685,11 +1849,11 @@ void Field::InternalSwap(Field* other) {
void Field::clear_kind() {
kind_ = 0;
}
- ::google::protobuf::Field_Kind Field::kind() const {
+::google::protobuf::Field_Kind Field::kind() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.kind)
return static_cast< ::google::protobuf::Field_Kind >(kind_);
}
- void Field::set_kind(::google::protobuf::Field_Kind value) {
+void Field::set_kind(::google::protobuf::Field_Kind value) {
kind_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Field.kind)
@@ -1699,11 +1863,11 @@ void Field::clear_kind() {
void Field::clear_cardinality() {
cardinality_ = 0;
}
- ::google::protobuf::Field_Cardinality Field::cardinality() const {
+::google::protobuf::Field_Cardinality Field::cardinality() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.cardinality)
return static_cast< ::google::protobuf::Field_Cardinality >(cardinality_);
}
- void Field::set_cardinality(::google::protobuf::Field_Cardinality value) {
+void Field::set_cardinality(::google::protobuf::Field_Cardinality value) {
cardinality_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Field.cardinality)
@@ -1713,11 +1877,11 @@ void Field::clear_cardinality() {
void Field::clear_number() {
number_ = 0;
}
- ::google::protobuf::int32 Field::number() const {
+::google::protobuf::int32 Field::number() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.number)
return number_;
}
- void Field::set_number(::google::protobuf::int32 value) {
+void Field::set_number(::google::protobuf::int32 value) {
number_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Field.number)
@@ -1725,101 +1889,145 @@ void Field::clear_number() {
// optional string name = 4;
void Field::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Field::name() const {
+const ::std::string& Field::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Field::set_name(const ::std::string& value) {
+void Field::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.name)
}
- void Field::set_name(const char* value) {
+void Field::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.name)
}
- void Field::set_name(const char* value, size_t size) {
+void Field::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.name)
}
- ::std::string* Field::mutable_name() {
+::std::string* Field::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Field::release_name() {
+::std::string* Field::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- void Field::set_allocated_name(::std::string* name) {
+::std::string* Field::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+void Field::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.name)
}
+void Field::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.name)
+}
// optional string type_url = 6;
void Field::clear_type_url() {
- type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_url_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Field::type_url() const {
+const ::std::string& Field::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.type_url)
- return type_url_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Field::set_type_url(const ::std::string& value) {
+void Field::set_type_url(const ::std::string& value) {
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.type_url)
}
- void Field::set_type_url(const char* value) {
+void Field::set_type_url(const char* value) {
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.type_url)
}
- void Field::set_type_url(const char* value, size_t size) {
+void Field::set_type_url(const char* value,
+ size_t size) {
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.type_url)
}
- ::std::string* Field::mutable_type_url() {
+::std::string* Field::mutable_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.type_url)
- return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Field::release_type_url() {
+::std::string* Field::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.type_url)
- return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- void Field::set_allocated_type_url(::std::string* type_url) {
+::std::string* Field::unsafe_arena_release_type_url() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.type_url)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return type_url_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+void Field::set_allocated_type_url(::std::string* type_url) {
if (type_url != NULL) {
} else {
}
- type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url);
+ type_url_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.type_url)
}
+void Field::unsafe_arena_set_allocated_type_url(
+ ::std::string* type_url) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (type_url != NULL) {
+
+ } else {
+
+ }
+ type_url_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ type_url, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.type_url)
+}
// optional int32 oneof_index = 7;
void Field::clear_oneof_index() {
oneof_index_ = 0;
}
- ::google::protobuf::int32 Field::oneof_index() const {
+::google::protobuf::int32 Field::oneof_index() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.oneof_index)
return oneof_index_;
}
- void Field::set_oneof_index(::google::protobuf::int32 value) {
+void Field::set_oneof_index(::google::protobuf::int32 value) {
oneof_index_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Field.oneof_index)
@@ -1829,11 +2037,11 @@ void Field::clear_oneof_index() {
void Field::clear_packed() {
packed_ = false;
}
- bool Field::packed() const {
+bool Field::packed() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.packed)
return packed_;
}
- void Field::set_packed(bool value) {
+void Field::set_packed(bool value) {
packed_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Field.packed)
@@ -1871,96 +2079,176 @@ Field::options() const {
// optional string json_name = 10;
void Field::clear_json_name() {
- json_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Field::json_name() const {
+const ::std::string& Field::json_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.json_name)
- return json_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Field::set_json_name(const ::std::string& value) {
+void Field::set_json_name(const ::std::string& value) {
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.json_name)
}
- void Field::set_json_name(const char* value) {
+void Field::set_json_name(const char* value) {
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.json_name)
}
- void Field::set_json_name(const char* value, size_t size) {
+void Field::set_json_name(const char* value,
+ size_t size) {
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.json_name)
}
- ::std::string* Field::mutable_json_name() {
+::std::string* Field::mutable_json_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.json_name)
- return json_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Field::release_json_name() {
+::std::string* Field::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.json_name)
- return json_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+::std::string* Field::unsafe_arena_release_json_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.json_name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
- void Field::set_allocated_json_name(::std::string* json_name) {
+void Field::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
} else {
}
- json_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name);
+ json_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.json_name)
}
+void Field::unsafe_arena_set_allocated_json_name(
+ ::std::string* json_name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (json_name != NULL) {
+
+ } else {
+
+ }
+ json_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ json_name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.json_name)
+}
// optional string default_value = 11;
void Field::clear_default_value() {
- default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Field::default_value() const {
+const ::std::string& Field::default_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.default_value)
- return default_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Field::set_default_value(const ::std::string& value) {
+void Field::set_default_value(const ::std::string& value) {
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.default_value)
}
- void Field::set_default_value(const char* value) {
+void Field::set_default_value(const char* value) {
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.default_value)
}
- void Field::set_default_value(const char* value, size_t size) {
+void Field::set_default_value(const char* value,
+ size_t size) {
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.default_value)
}
- ::std::string* Field::mutable_default_value() {
+::std::string* Field::mutable_default_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.default_value)
- return default_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Field::release_default_value() {
+::std::string* Field::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.default_value)
- return default_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+::std::string* Field::unsafe_arena_release_default_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.default_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
- void Field::set_allocated_default_value(::std::string* default_value) {
+void Field::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
} else {
}
- default_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value);
+ default_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.default_value)
}
+void Field::unsafe_arena_set_allocated_default_value(
+ ::std::string* default_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (default_value != NULL) {
+
+ } else {
+
+ }
+ default_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ default_value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.default_value)
+}
+inline const Field* Field::internal_default_instance() {
+ return &Field_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Enum::_slow_mutable_source_context() {
+ source_context_ = ::google::protobuf::Arena::Create< ::google::protobuf::SourceContext >(
+ GetArenaNoVirtual());
+}
+::google::protobuf::SourceContext* Enum::_slow_release_source_context() {
+ if (source_context_ == NULL) {
+ return NULL;
+ } else {
+ ::google::protobuf::SourceContext* temp = new ::google::protobuf::SourceContext(*source_context_);
+ source_context_ = NULL;
+ return temp;
+ }
+}
+::google::protobuf::SourceContext* Enum::unsafe_arena_release_source_context() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.source_context)
+
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
+}
+void Enum::unsafe_arena_set_allocated_source_context(
+ ::google::protobuf::SourceContext* source_context) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete source_context_;
+ }
+ source_context_ = source_context;
+ if (source_context) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.source_context)
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Enum::kNameFieldNumber;
const int Enum::kEnumvalueFieldNumber;
@@ -1971,30 +2259,41 @@ const int Enum::kSyntaxFieldNumber;
Enum::Enum()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Enum)
}
+Enum::Enum(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ enumvalue_(arena),
+ options_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Enum)
+}
void Enum::InitAsDefaultInstance() {
- _is_default_instance_ = true;
- source_context_ = const_cast< ::google::protobuf::SourceContext*>(&::google::protobuf::SourceContext::default_instance());
+ source_context_ = const_cast< ::google::protobuf::SourceContext*>(
+ ::google::protobuf::SourceContext::internal_default_instance());
}
Enum::Enum(const Enum& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Enum)
}
void Enum::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
source_context_ = NULL;
syntax_ = 0;
+ _cached_size_ = 0;
}
Enum::~Enum() {
@@ -2003,12 +2302,23 @@ Enum::~Enum() {
}
void Enum::SharedDtor() {
- name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
+ }
+
+ name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ if (this != &Enum_default_instance_.get()) {
delete source_context_;
}
}
+void Enum::ArenaDtor(void* object) {
+ Enum* _this = reinterpret_cast< Enum* >(object);
+ (void)_this;
+}
+void Enum::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Enum::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -2020,23 +2330,19 @@ const ::google::protobuf::Descriptor* Enum::descriptor() {
}
const Enum& Enum::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ return *internal_default_instance();
}
-Enum* Enum::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Enum> Enum_default_instance_;
Enum* Enum::New(::google::protobuf::Arena* arena) const {
- Enum* n = new Enum;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Enum>(arena);
}
void Enum::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Enum)
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
source_context_ = NULL;
syntax_ = 0;
@@ -2195,6 +2501,7 @@ void Enum::SerializeWithCachedSizes(
::google::protobuf::uint8* Enum::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Enum)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -2238,9 +2545,9 @@ void Enum::SerializeWithCachedSizes(
return target;
}
-int Enum::ByteSize() const {
+size_t Enum::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Enum)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -2263,33 +2570,38 @@ int Enum::ByteSize() const {
}
// repeated .google.protobuf.EnumValue enumvalue = 2;
- total_size += 1 * this->enumvalue_size();
- for (int i = 0; i < this->enumvalue_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->enumvalue(i));
+ {
+ unsigned int count = this->enumvalue_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->enumvalue(i));
+ }
}
// repeated .google.protobuf.Option options = 3;
- total_size += 1 * this->options_size();
- for (int i = 0; i < this->options_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ {
+ unsigned int count = this->options_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->options(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Enum::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Enum)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Enum* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Enum* source =
::google::protobuf::internal::DynamicCastToGenerated<const Enum>(
&from);
if (source == NULL) {
@@ -2297,20 +2609,25 @@ void Enum::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Enum)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Enum::MergeFrom(const Enum& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Enum)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Enum::UnsafeMergeFrom(const Enum& from) {
+ GOOGLE_DCHECK(&from != this);
enumvalue_.MergeFrom(from.enumvalue_);
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ set_name(from.name());
}
if (from.has_source_context()) {
mutable_source_context()->::google::protobuf::SourceContext::MergeFrom(from.source_context());
@@ -2331,7 +2648,7 @@ void Enum::CopyFrom(const Enum& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Enum)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Enum::IsInitialized() const {
@@ -2341,6 +2658,18 @@ bool Enum::IsInitialized() const {
void Enum::Swap(Enum* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Enum temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Enum::UnsafeArenaSwap(Enum* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Enum::InternalSwap(Enum* other) {
@@ -2366,47 +2695,69 @@ void Enum::InternalSwap(Enum* other) {
// optional string name = 1;
void Enum::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Enum::name() const {
+const ::std::string& Enum::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Enum.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Enum::set_name(const ::std::string& value) {
+void Enum::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Enum.name)
}
- void Enum::set_name(const char* value) {
+void Enum::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Enum.name)
}
- void Enum::set_name(const char* value, size_t size) {
+void Enum::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Enum.name)
}
- ::std::string* Enum::mutable_name() {
+::std::string* Enum::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Enum::release_name() {
+::std::string* Enum::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Enum.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+::std::string* Enum::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
- void Enum::set_allocated_name(::std::string* name) {
+void Enum::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.name)
}
+void Enum::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.name)
+}
// repeated .google.protobuf.EnumValue enumvalue = 2;
int Enum::enumvalue_size() const {
@@ -2470,7 +2821,7 @@ Enum::options() const {
// optional .google.protobuf.SourceContext source_context = 4;
bool Enum::has_source_context() const {
- return !_is_default_instance_ && source_context_ != NULL;
+ return this != internal_default_instance() && source_context_ != NULL;
}
void Enum::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
@@ -2478,12 +2829,13 @@ void Enum::clear_source_context() {
}
const ::google::protobuf::SourceContext& Enum::source_context() const {
// @@protoc_insertion_point(field_get:google.protobuf.Enum.source_context)
- return source_context_ != NULL ? *source_context_ : *default_instance_->source_context_;
+ return source_context_ != NULL ? *source_context_
+ : *::google::protobuf::SourceContext::internal_default_instance();
}
::google::protobuf::SourceContext* Enum::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = new ::google::protobuf::SourceContext;
+ _slow_mutable_source_context();
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context)
return source_context_;
@@ -2491,12 +2843,24 @@ const ::google::protobuf::SourceContext& Enum::source_context() const {
::google::protobuf::SourceContext* Enum::release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Enum.source_context)
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ return _slow_release_source_context();
+ } else {
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
+ }
}
-void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- delete source_context_;
+ void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete source_context_;
+ }
+ if (source_context != NULL) {
+ if (message_arena != NULL) {
+ message_arena->Own(source_context);
+ }
+ }
source_context_ = source_context;
if (source_context) {
@@ -2510,16 +2874,19 @@ void Enum::set_allocated_source_context(::google::protobuf::SourceContext* sourc
void Enum::clear_syntax() {
syntax_ = 0;
}
- ::google::protobuf::Syntax Enum::syntax() const {
+::google::protobuf::Syntax Enum::syntax() const {
// @@protoc_insertion_point(field_get:google.protobuf.Enum.syntax)
return static_cast< ::google::protobuf::Syntax >(syntax_);
}
- void Enum::set_syntax(::google::protobuf::Syntax value) {
+void Enum::set_syntax(::google::protobuf::Syntax value) {
syntax_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Enum.syntax)
}
+inline const Enum* Enum::internal_default_instance() {
+ return &Enum_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -2532,28 +2899,37 @@ const int EnumValue::kOptionsFieldNumber;
EnumValue::EnumValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.EnumValue)
}
+EnumValue::EnumValue(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena),
+ options_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue)
+}
void EnumValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
EnumValue::EnumValue(const EnumValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValue)
}
void EnumValue::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
number_ = 0;
+ _cached_size_ = 0;
}
EnumValue::~EnumValue() {
@@ -2562,11 +2938,20 @@ EnumValue::~EnumValue() {
}
void EnumValue::SharedDtor() {
- name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
}
+
+ name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
}
+void EnumValue::ArenaDtor(void* object) {
+ EnumValue* _this = reinterpret_cast< EnumValue* >(object);
+ (void)_this;
+}
+void EnumValue::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void EnumValue::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -2578,23 +2963,19 @@ const ::google::protobuf::Descriptor* EnumValue::descriptor() {
}
const EnumValue& EnumValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ return *internal_default_instance();
}
-EnumValue* EnumValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<EnumValue> EnumValue_default_instance_;
EnumValue* EnumValue::New(::google::protobuf::Arena* arena) const {
- EnumValue* n = new EnumValue;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<EnumValue>(arena);
}
void EnumValue::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.EnumValue)
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
number_ = 0;
options_.Clear();
}
@@ -2629,10 +3010,10 @@ bool EnumValue::MergePartialFromCodedStream(
case 2: {
if (tag == 16) {
parse_number:
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &number_)));
-
} else {
goto handle_unusual;
}
@@ -2707,6 +3088,7 @@ void EnumValue::SerializeWithCachedSizes(
::google::protobuf::uint8* EnumValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.EnumValue)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -2735,9 +3117,9 @@ void EnumValue::SerializeWithCachedSizes(
return target;
}
-int EnumValue::ByteSize() const {
+size_t EnumValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumValue)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -2754,25 +3136,27 @@ int EnumValue::ByteSize() const {
}
// repeated .google.protobuf.Option options = 3;
- total_size += 1 * this->options_size();
- for (int i = 0; i < this->options_size(); i++) {
- total_size +=
- ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
- this->options(i));
+ {
+ unsigned int count = this->options_size();
+ total_size += 1UL * count;
+ for (unsigned int i = 0; i < count; i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->options(i));
+ }
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void EnumValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.EnumValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const EnumValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const EnumValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const EnumValue>(
&from);
if (source == NULL) {
@@ -2780,19 +3164,24 @@ void EnumValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.EnumValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void EnumValue::MergeFrom(const EnumValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.EnumValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void EnumValue::UnsafeMergeFrom(const EnumValue& from) {
+ GOOGLE_DCHECK(&from != this);
options_.MergeFrom(from.options_);
if (from.name().size() > 0) {
-
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+ set_name(from.name());
}
if (from.number() != 0) {
set_number(from.number());
@@ -2810,7 +3199,7 @@ void EnumValue::CopyFrom(const EnumValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.EnumValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool EnumValue::IsInitialized() const {
@@ -2820,6 +3209,18 @@ bool EnumValue::IsInitialized() const {
void EnumValue::Swap(EnumValue* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ EnumValue temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void EnumValue::UnsafeArenaSwap(EnumValue* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void EnumValue::InternalSwap(EnumValue* other) {
@@ -2843,57 +3244,79 @@ void EnumValue::InternalSwap(EnumValue* other) {
// optional string name = 1;
void EnumValue::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& EnumValue::name() const {
+const ::std::string& EnumValue::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValue.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void EnumValue::set_name(const ::std::string& value) {
+void EnumValue::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.EnumValue.name)
}
- void EnumValue::set_name(const char* value) {
+void EnumValue::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumValue.name)
}
- void EnumValue::set_name(const char* value, size_t size) {
+void EnumValue::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValue.name)
}
- ::std::string* EnumValue::mutable_name() {
+::std::string* EnumValue::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValue.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* EnumValue::release_name() {
+::std::string* EnumValue::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValue.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- void EnumValue::set_allocated_name(::std::string* name) {
+::std::string* EnumValue::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValue.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+void EnumValue::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValue.name)
}
+void EnumValue::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValue.name)
+}
// optional int32 number = 2;
void EnumValue::clear_number() {
number_ = 0;
}
- ::google::protobuf::int32 EnumValue::number() const {
+::google::protobuf::int32 EnumValue::number() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValue.number)
return number_;
}
- void EnumValue::set_number(::google::protobuf::int32 value) {
+void EnumValue::set_number(::google::protobuf::int32 value) {
number_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.EnumValue.number)
@@ -2929,10 +3352,46 @@ EnumValue::options() const {
return options_;
}
+inline const EnumValue* EnumValue::internal_default_instance() {
+ return &EnumValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
+void Option::_slow_mutable_value() {
+ value_ = ::google::protobuf::Arena::Create< ::google::protobuf::Any >(
+ GetArenaNoVirtual());
+}
+::google::protobuf::Any* Option::_slow_release_value() {
+ if (value_ == NULL) {
+ return NULL;
+ } else {
+ ::google::protobuf::Any* temp = new ::google::protobuf::Any(*value_);
+ value_ = NULL;
+ return temp;
+ }
+}
+::google::protobuf::Any* Option::unsafe_arena_release_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.value)
+
+ ::google::protobuf::Any* temp = value_;
+ value_ = NULL;
+ return temp;
+}
+void Option::unsafe_arena_set_allocated_value(
+ ::google::protobuf::Any* value) {
+ if (GetArenaNoVirtual() == NULL) {
+ delete value_;
+ }
+ value_ = value;
+ if (value) {
+
+ } else {
+
+ }
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.value)
+}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Option::kNameFieldNumber;
const int Option::kValueFieldNumber;
@@ -2940,29 +3399,38 @@ const int Option::kValueFieldNumber;
Option::Option()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Option)
}
+Option::Option(::google::protobuf::Arena* arena)
+ : ::google::protobuf::Message(),
+ _internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ SharedCtor();
+ RegisterArenaDtor(arena);
+ // @@protoc_insertion_point(arena_constructor:google.protobuf.Option)
+}
void Option::InitAsDefaultInstance() {
- _is_default_instance_ = true;
- value_ = const_cast< ::google::protobuf::Any*>(&::google::protobuf::Any::default_instance());
+ value_ = const_cast< ::google::protobuf::Any*>(
+ ::google::protobuf::Any::internal_default_instance());
}
Option::Option(const Option& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Option)
}
void Option::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_ = NULL;
+ _cached_size_ = 0;
}
Option::~Option() {
@@ -2971,12 +3439,23 @@ Option::~Option() {
}
void Option::SharedDtor() {
- name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
- if (this != default_instance_) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
+ return;
+ }
+
+ name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
+ if (this != &Option_default_instance_.get()) {
delete value_;
}
}
+void Option::ArenaDtor(void* object) {
+ Option* _this = reinterpret_cast< Option* >(object);
+ (void)_this;
+}
+void Option::RegisterArenaDtor(::google::protobuf::Arena* arena) {
+}
void Option::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
@@ -2988,23 +3467,19 @@ const ::google::protobuf::Descriptor* Option::descriptor() {
}
const Option& Option::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
+ return *internal_default_instance();
}
-Option* Option::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Option> Option_default_instance_;
Option* Option::New(::google::protobuf::Arena* arena) const {
- Option* n = new Option;
- if (arena != NULL) {
- arena->Own(n);
- }
- return n;
+ return ::google::protobuf::Arena::CreateMessage<Option>(arena);
}
void Option::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Option)
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == NULL && value_ != NULL) delete value_;
value_ = NULL;
}
@@ -3093,6 +3568,7 @@ void Option::SerializeWithCachedSizes(
::google::protobuf::uint8* Option::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Option)
// optional string name = 1;
if (this->name().size() > 0) {
@@ -3116,9 +3592,9 @@ void Option::SerializeWithCachedSizes(
return target;
}
-int Option::ByteSize() const {
+size_t Option::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Option)
- int total_size = 0;
+ size_t total_size = 0;
// optional string name = 1;
if (this->name().size() > 0) {
@@ -3134,18 +3610,17 @@ int Option::ByteSize() const {
*this->value_);
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Option::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Option)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Option* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Option* source =
::google::protobuf::internal::DynamicCastToGenerated<const Option>(
&from);
if (source == NULL) {
@@ -3153,18 +3628,23 @@ void Option::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Option)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Option::MergeFrom(const Option& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Option)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
- if (from.name().size() > 0) {
+}
- name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
+void Option::UnsafeMergeFrom(const Option& from) {
+ GOOGLE_DCHECK(&from != this);
+ if (from.name().size() > 0) {
+ set_name(from.name());
}
if (from.has_value()) {
mutable_value()->::google::protobuf::Any::MergeFrom(from.value());
@@ -3182,7 +3662,7 @@ void Option::CopyFrom(const Option& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Option)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Option::IsInitialized() const {
@@ -3192,6 +3672,18 @@ bool Option::IsInitialized() const {
void Option::Swap(Option* other) {
if (other == this) return;
+ if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
+ InternalSwap(other);
+ } else {
+ Option temp;
+ temp.UnsafeMergeFrom(*this);
+ CopyFrom(*other);
+ other->CopyFrom(temp);
+ }
+}
+void Option::UnsafeArenaSwap(Option* other) {
+ if (other == this) return;
+ GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Option::InternalSwap(Option* other) {
@@ -3214,51 +3706,73 @@ void Option::InternalSwap(Option* other) {
// optional string name = 1;
void Option::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& Option::name() const {
+const ::std::string& Option::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Option.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void Option::set_name(const ::std::string& value) {
+void Option::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Option.name)
}
- void Option::set_name(const char* value) {
+void Option::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Option.name)
}
- void Option::set_name(const char* value, size_t size) {
+void Option::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Option.name)
}
- ::std::string* Option::mutable_name() {
+::std::string* Option::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* Option::release_name() {
+::std::string* Option::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Option.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- void Option::set_allocated_name(::std::string* name) {
+::std::string* Option::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
+}
+void Option::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.name)
}
+void Option::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.name)
+}
// optional .google.protobuf.Any value = 2;
bool Option::has_value() const {
- return !_is_default_instance_ && value_ != NULL;
+ return this != internal_default_instance() && value_ != NULL;
}
void Option::clear_value() {
if (GetArenaNoVirtual() == NULL && value_ != NULL) delete value_;
@@ -3266,12 +3780,13 @@ void Option::clear_value() {
}
const ::google::protobuf::Any& Option::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Option.value)
- return value_ != NULL ? *value_ : *default_instance_->value_;
+ return value_ != NULL ? *value_
+ : *::google::protobuf::Any::internal_default_instance();
}
::google::protobuf::Any* Option::mutable_value() {
if (value_ == NULL) {
- value_ = new ::google::protobuf::Any;
+ _slow_mutable_value();
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.value)
return value_;
@@ -3279,12 +3794,24 @@ const ::google::protobuf::Any& Option::value() const {
::google::protobuf::Any* Option::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Option.value)
- ::google::protobuf::Any* temp = value_;
- value_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ return _slow_release_value();
+ } else {
+ ::google::protobuf::Any* temp = value_;
+ value_ = NULL;
+ return temp;
+ }
}
-void Option::set_allocated_value(::google::protobuf::Any* value) {
- delete value_;
+ void Option::set_allocated_value(::google::protobuf::Any* value) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete value_;
+ }
+ if (value != NULL) {
+ if (message_arena != NULL) {
+ message_arena->Own(value);
+ }
+ }
value_ = value;
if (value) {
@@ -3294,6 +3821,9 @@ void Option::set_allocated_value(::google::protobuf::Any* value) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.value)
}
+inline const Option* Option::internal_default_instance() {
+ return &Option_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h
index ce29c281..1b6d3410 100644
--- a/src/google/protobuf/type.pb.h
+++ b/src/google/protobuf/type.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -37,6 +37,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
@@ -142,9 +143,16 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Type& default_instance();
+ static const Type* internal_default_instance();
+
+ void UnsafeArenaSwap(Type* other);
void Swap(Type* other);
// implements Message ----------------------------------------------
@@ -159,7 +167,7 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -175,6 +183,12 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Type* other);
+ void UnsafeMergeFrom(const Type& from);
+ protected:
+ explicit Type(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -200,6 +214,9 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ ::std::string* unsafe_arena_release_name();
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// repeated .google.protobuf.Field fields = 2;
int fields_size() const;
@@ -245,10 +262,17 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
+ private:
+ void _slow_mutable_source_context();
+ ::google::protobuf::SourceContext* _slow_release_source_context();
+ public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* mutable_source_context();
::google::protobuf::SourceContext* release_source_context();
void set_allocated_source_context(::google::protobuf::SourceContext* source_context);
+ ::google::protobuf::SourceContext* unsafe_arena_release_source_context();
+ void unsafe_arena_set_allocated_source_context(
+ ::google::protobuf::SourceContext* source_context);
// optional .google.protobuf.Syntax syntax = 6;
void clear_syntax();
@@ -260,21 +284,25 @@ class LIBPROTOBUF_EXPORT Type : public ::google::protobuf::Message /* @@protoc_i
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
- ::google::protobuf::internal::ArenaStringPtr name_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Field > fields_;
::google::protobuf::RepeatedPtrField< ::std::string> oneofs_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
void InitAsDefaultInstance();
- static Type* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Type> Type_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Field) */ {
@@ -289,9 +317,16 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Field& default_instance();
+ static const Field* internal_default_instance();
+
+ void UnsafeArenaSwap(Field* other);
void Swap(Field* other);
// implements Message ----------------------------------------------
@@ -306,7 +341,7 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -322,6 +357,12 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Field* other);
+ void UnsafeMergeFrom(const Field& from);
+ protected:
+ explicit Field(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -455,6 +496,9 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ ::std::string* unsafe_arena_release_name();
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// optional string type_url = 6;
void clear_type_url();
@@ -466,6 +510,9 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::std::string* mutable_type_url();
::std::string* release_type_url();
void set_allocated_type_url(::std::string* type_url);
+ ::std::string* unsafe_arena_release_type_url();
+ void unsafe_arena_set_allocated_type_url(
+ ::std::string* type_url);
// optional int32 oneof_index = 7;
void clear_oneof_index();
@@ -501,6 +548,9 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::std::string* mutable_json_name();
::std::string* release_json_name();
void set_allocated_json_name(::std::string* json_name);
+ ::std::string* unsafe_arena_release_json_name();
+ void unsafe_arena_set_allocated_json_name(
+ ::std::string* json_name);
// optional string default_value = 11;
void clear_default_value();
@@ -512,30 +562,37 @@ class LIBPROTOBUF_EXPORT Field : public ::google::protobuf::Message /* @@protoc_
::std::string* mutable_default_value();
::std::string* release_default_value();
void set_allocated_default_value(::std::string* default_value);
+ ::std::string* unsafe_arena_release_default_value();
+ void unsafe_arena_set_allocated_default_value(
+ ::std::string* default_value);
// @@protoc_insertion_point(class_scope:google.protobuf.Field)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
- int kind_;
- int cardinality_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
+ ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
::google::protobuf::internal::ArenaStringPtr name_;
- ::google::protobuf::int32 number_;
- ::google::protobuf::int32 oneof_index_;
::google::protobuf::internal::ArenaStringPtr type_url_;
- ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
::google::protobuf::internal::ArenaStringPtr json_name_;
::google::protobuf::internal::ArenaStringPtr default_value_;
+ int kind_;
+ int cardinality_;
+ ::google::protobuf::int32 number_;
+ ::google::protobuf::int32 oneof_index_;
bool packed_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
void InitAsDefaultInstance();
- static Field* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Field> Field_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Enum) */ {
@@ -550,9 +607,16 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Enum& default_instance();
+ static const Enum* internal_default_instance();
+
+ void UnsafeArenaSwap(Enum* other);
void Swap(Enum* other);
// implements Message ----------------------------------------------
@@ -567,7 +631,7 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -583,6 +647,12 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Enum* other);
+ void UnsafeMergeFrom(const Enum& from);
+ protected:
+ explicit Enum(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -608,6 +678,9 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ ::std::string* unsafe_arena_release_name();
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// repeated .google.protobuf.EnumValue enumvalue = 2;
int enumvalue_size() const;
@@ -637,10 +710,17 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 4;
+ private:
+ void _slow_mutable_source_context();
+ ::google::protobuf::SourceContext* _slow_release_source_context();
+ public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* mutable_source_context();
::google::protobuf::SourceContext* release_source_context();
void set_allocated_source_context(::google::protobuf::SourceContext* source_context);
+ ::google::protobuf::SourceContext* unsafe_arena_release_source_context();
+ void unsafe_arena_set_allocated_source_context(
+ ::google::protobuf::SourceContext* source_context);
// optional .google.protobuf.Syntax syntax = 5;
void clear_syntax();
@@ -652,20 +732,24 @@ class LIBPROTOBUF_EXPORT Enum : public ::google::protobuf::Message /* @@protoc_i
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
- ::google::protobuf::internal::ArenaStringPtr name_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValue > enumvalue_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
void InitAsDefaultInstance();
- static Enum* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Enum> Enum_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValue) */ {
@@ -680,9 +764,16 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const EnumValue& default_instance();
+ static const EnumValue* internal_default_instance();
+
+ void UnsafeArenaSwap(EnumValue* other);
void Swap(EnumValue* other);
// implements Message ----------------------------------------------
@@ -697,7 +788,7 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -713,6 +804,12 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(EnumValue* other);
+ void UnsafeMergeFrom(const EnumValue& from);
+ protected:
+ explicit EnumValue(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -738,6 +835,9 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ ::std::string* unsafe_arena_release_name();
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// optional int32 number = 2;
void clear_number();
@@ -761,18 +861,22 @@ class LIBPROTOBUF_EXPORT EnumValue : public ::google::protobuf::Message /* @@pro
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
- ::google::protobuf::internal::ArenaStringPtr name_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_;
+ ::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::int32 number_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
void InitAsDefaultInstance();
- static EnumValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<EnumValue> EnumValue_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Option) */ {
@@ -787,9 +891,16 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
return *this;
}
+ inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
+ inline void* GetMaybeArenaPointer() const {
+ return MaybeArenaPtr();
+ }
static const ::google::protobuf::Descriptor* descriptor();
static const Option& default_instance();
+ static const Option* internal_default_instance();
+
+ void UnsafeArenaSwap(Option* other);
void Swap(Option* other);
// implements Message ----------------------------------------------
@@ -804,7 +915,7 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -820,6 +931,12 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Option* other);
+ void UnsafeMergeFrom(const Option& from);
+ protected:
+ explicit Option(::google::protobuf::Arena* arena);
+ private:
+ static void ArenaDtor(void* object);
+ inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
@@ -845,31 +962,45 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);
+ ::std::string* unsafe_arena_release_name();
+ void unsafe_arena_set_allocated_name(
+ ::std::string* name);
// optional .google.protobuf.Any value = 2;
bool has_value() const;
void clear_value();
static const int kValueFieldNumber = 2;
+ private:
+ void _slow_mutable_value();
+ ::google::protobuf::Any* _slow_release_value();
+ public:
const ::google::protobuf::Any& value() const;
::google::protobuf::Any* mutable_value();
::google::protobuf::Any* release_value();
void set_allocated_value(::google::protobuf::Any* value);
+ ::google::protobuf::Any* unsafe_arena_release_value();
+ void unsafe_arena_set_allocated_value(
+ ::google::protobuf::Any* value);
// @@protoc_insertion_point(class_scope:google.protobuf.Option)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
- bool _is_default_instance_;
+ friend class ::google::protobuf::Arena;
+ typedef void InternalArenaConstructable_;
+ typedef void DestructorSkippable_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::Any* value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2ftype_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2ftype_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2ftype_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2ftype_2eproto();
void InitAsDefaultInstance();
- static Option* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Option> Option_default_instance_;
+
// ===================================================================
@@ -880,37 +1011,46 @@ class LIBPROTOBUF_EXPORT Option : public ::google::protobuf::Message /* @@protoc
// optional string name = 1;
inline void Type::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Type::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Type::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Type.name)
}
inline void Type::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Type.name)
}
-inline void Type::set_name(const char* value, size_t size) {
+inline void Type::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.name)
}
inline ::std::string* Type::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Type::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Type.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Type::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Type.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Type::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -918,9 +1058,22 @@ inline void Type::set_allocated_name(::std::string* name) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.name)
}
+inline void Type::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Type.name)
+}
// repeated .google.protobuf.Field fields = 2;
inline int Type::fields_size() const {
@@ -1039,7 +1192,7 @@ Type::options() const {
// optional .google.protobuf.SourceContext source_context = 5;
inline bool Type::has_source_context() const {
- return !_is_default_instance_ && source_context_ != NULL;
+ return this != internal_default_instance() && source_context_ != NULL;
}
inline void Type::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
@@ -1047,12 +1200,13 @@ inline void Type::clear_source_context() {
}
inline const ::google::protobuf::SourceContext& Type::source_context() const {
// @@protoc_insertion_point(field_get:google.protobuf.Type.source_context)
- return source_context_ != NULL ? *source_context_ : *default_instance_->source_context_;
+ return source_context_ != NULL ? *source_context_
+ : *::google::protobuf::SourceContext::internal_default_instance();
}
inline ::google::protobuf::SourceContext* Type::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = new ::google::protobuf::SourceContext;
+ _slow_mutable_source_context();
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Type.source_context)
return source_context_;
@@ -1060,12 +1214,24 @@ inline ::google::protobuf::SourceContext* Type::mutable_source_context() {
inline ::google::protobuf::SourceContext* Type::release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Type.source_context)
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ return _slow_release_source_context();
+ } else {
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
+ }
}
-inline void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- delete source_context_;
+inline void Type::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete source_context_;
+ }
+ if (source_context != NULL) {
+ if (message_arena != NULL) {
+ message_arena->Own(source_context);
+ }
+ }
source_context_ = source_context;
if (source_context) {
@@ -1089,6 +1255,9 @@ inline void Type::set_syntax(::google::protobuf::Syntax value) {
// @@protoc_insertion_point(field_set:google.protobuf.Type.syntax)
}
+inline const Type* Type::internal_default_instance() {
+ return &Type_default_instance_.get();
+}
// -------------------------------------------------------------------
// Field
@@ -1137,37 +1306,46 @@ inline void Field::set_number(::google::protobuf::int32 value) {
// optional string name = 4;
inline void Field::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Field::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Field::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.name)
}
inline void Field::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.name)
}
-inline void Field::set_name(const char* value, size_t size) {
+inline void Field::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.name)
}
inline ::std::string* Field::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Field::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Field::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Field::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1175,43 +1353,65 @@ inline void Field::set_allocated_name(::std::string* name) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.name)
}
+inline void Field::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.name)
+}
// optional string type_url = 6;
inline void Field::clear_type_url() {
- type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_url_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Field::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.type_url)
- return type_url_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Field::set_type_url(const ::std::string& value) {
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.type_url)
}
inline void Field::set_type_url(const char* value) {
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.type_url)
}
-inline void Field::set_type_url(const char* value, size_t size) {
+inline void Field::set_type_url(const char* value,
+ size_t size) {
- type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ type_url_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.type_url)
}
inline ::std::string* Field::mutable_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.type_url)
- return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Field::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.type_url)
- return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return type_url_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Field::unsafe_arena_release_type_url() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.type_url)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return type_url_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Field::set_allocated_type_url(::std::string* type_url) {
if (type_url != NULL) {
@@ -1219,9 +1419,22 @@ inline void Field::set_allocated_type_url(::std::string* type_url) {
} else {
}
- type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url);
+ type_url_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.type_url)
}
+inline void Field::unsafe_arena_set_allocated_type_url(
+ ::std::string* type_url) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (type_url != NULL) {
+
+ } else {
+
+ }
+ type_url_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ type_url, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.type_url)
+}
// optional int32 oneof_index = 7;
inline void Field::clear_oneof_index() {
@@ -1283,37 +1496,46 @@ Field::options() const {
// optional string json_name = 10;
inline void Field::clear_json_name() {
- json_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ json_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Field::json_name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.json_name)
- return json_name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Field::set_json_name(const ::std::string& value) {
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.json_name)
}
inline void Field::set_json_name(const char* value) {
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.json_name)
}
-inline void Field::set_json_name(const char* value, size_t size) {
+inline void Field::set_json_name(const char* value,
+ size_t size) {
- json_name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ json_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.json_name)
}
inline ::std::string* Field::mutable_json_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.json_name)
- return json_name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Field::release_json_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.json_name)
- return json_name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return json_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Field::unsafe_arena_release_json_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.json_name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return json_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Field::set_allocated_json_name(::std::string* json_name) {
if (json_name != NULL) {
@@ -1321,43 +1543,65 @@ inline void Field::set_allocated_json_name(::std::string* json_name) {
} else {
}
- json_name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name);
+ json_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), json_name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.json_name)
}
+inline void Field::unsafe_arena_set_allocated_json_name(
+ ::std::string* json_name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (json_name != NULL) {
+
+ } else {
+
+ }
+ json_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ json_name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.json_name)
+}
// optional string default_value = 11;
inline void Field::clear_default_value() {
- default_value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ default_value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Field::default_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Field.default_value)
- return default_value_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Field::set_default_value(const ::std::string& value) {
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Field.default_value)
}
inline void Field::set_default_value(const char* value) {
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Field.default_value)
}
-inline void Field::set_default_value(const char* value, size_t size) {
+inline void Field::set_default_value(const char* value,
+ size_t size) {
- default_value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ default_value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Field.default_value)
}
inline ::std::string* Field::mutable_default_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Field.default_value)
- return default_value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Field::release_default_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Field.default_value)
- return default_value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return default_value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Field::unsafe_arena_release_default_value() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Field.default_value)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return default_value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Field::set_allocated_default_value(::std::string* default_value) {
if (default_value != NULL) {
@@ -1365,47 +1609,72 @@ inline void Field::set_allocated_default_value(::std::string* default_value) {
} else {
}
- default_value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value);
+ default_value_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), default_value,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.default_value)
}
+inline void Field::unsafe_arena_set_allocated_default_value(
+ ::std::string* default_value) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (default_value != NULL) {
+
+ } else {
+
+ }
+ default_value_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ default_value, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Field.default_value)
+}
+inline const Field* Field::internal_default_instance() {
+ return &Field_default_instance_.get();
+}
// -------------------------------------------------------------------
// Enum
// optional string name = 1;
inline void Enum::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Enum::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Enum.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Enum::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Enum.name)
}
inline void Enum::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Enum.name)
}
-inline void Enum::set_name(const char* value, size_t size) {
+inline void Enum::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Enum.name)
}
inline ::std::string* Enum::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Enum::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Enum.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Enum::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Enum.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Enum::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1413,9 +1682,22 @@ inline void Enum::set_allocated_name(::std::string* name) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.name)
}
+inline void Enum::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Enum.name)
+}
// repeated .google.protobuf.EnumValue enumvalue = 2;
inline int Enum::enumvalue_size() const {
@@ -1479,7 +1761,7 @@ Enum::options() const {
// optional .google.protobuf.SourceContext source_context = 4;
inline bool Enum::has_source_context() const {
- return !_is_default_instance_ && source_context_ != NULL;
+ return this != internal_default_instance() && source_context_ != NULL;
}
inline void Enum::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
@@ -1487,12 +1769,13 @@ inline void Enum::clear_source_context() {
}
inline const ::google::protobuf::SourceContext& Enum::source_context() const {
// @@protoc_insertion_point(field_get:google.protobuf.Enum.source_context)
- return source_context_ != NULL ? *source_context_ : *default_instance_->source_context_;
+ return source_context_ != NULL ? *source_context_
+ : *::google::protobuf::SourceContext::internal_default_instance();
}
inline ::google::protobuf::SourceContext* Enum::mutable_source_context() {
if (source_context_ == NULL) {
- source_context_ = new ::google::protobuf::SourceContext;
+ _slow_mutable_source_context();
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Enum.source_context)
return source_context_;
@@ -1500,12 +1783,24 @@ inline ::google::protobuf::SourceContext* Enum::mutable_source_context() {
inline ::google::protobuf::SourceContext* Enum::release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Enum.source_context)
- ::google::protobuf::SourceContext* temp = source_context_;
- source_context_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ return _slow_release_source_context();
+ } else {
+ ::google::protobuf::SourceContext* temp = source_context_;
+ source_context_ = NULL;
+ return temp;
+ }
}
-inline void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
- delete source_context_;
+inline void Enum::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete source_context_;
+ }
+ if (source_context != NULL) {
+ if (message_arena != NULL) {
+ message_arena->Own(source_context);
+ }
+ }
source_context_ = source_context;
if (source_context) {
@@ -1529,43 +1824,55 @@ inline void Enum::set_syntax(::google::protobuf::Syntax value) {
// @@protoc_insertion_point(field_set:google.protobuf.Enum.syntax)
}
+inline const Enum* Enum::internal_default_instance() {
+ return &Enum_default_instance_.get();
+}
// -------------------------------------------------------------------
// EnumValue
// optional string name = 1;
inline void EnumValue::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& EnumValue::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.EnumValue.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void EnumValue::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.EnumValue.name)
}
inline void EnumValue::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.EnumValue.name)
}
-inline void EnumValue::set_name(const char* value, size_t size) {
+inline void EnumValue::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumValue.name)
}
inline ::std::string* EnumValue::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.EnumValue.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* EnumValue::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.EnumValue.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* EnumValue::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.EnumValue.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void EnumValue::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1573,9 +1880,22 @@ inline void EnumValue::set_allocated_name(::std::string* name) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValue.name)
}
+inline void EnumValue::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValue.name)
+}
// optional int32 number = 2;
inline void EnumValue::clear_number() {
@@ -1621,43 +1941,55 @@ EnumValue::options() const {
return options_;
}
+inline const EnumValue* EnumValue::internal_default_instance() {
+ return &EnumValue_default_instance_.get();
+}
// -------------------------------------------------------------------
// Option
// optional string name = 1;
inline void Option::clear_name() {
- name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline const ::std::string& Option::name() const {
// @@protoc_insertion_point(field_get:google.protobuf.Option.name)
- return name_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void Option::set_name(const ::std::string& value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.Option.name)
}
inline void Option::set_name(const char* value) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.Option.name)
}
-inline void Option::set_name(const char* value, size_t size) {
+inline void Option::set_name(const char* value,
+ size_t size) {
- name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
- ::std::string(reinterpret_cast<const char*>(value), size));
+ name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
+ reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Option.name)
}
inline ::std::string* Option::mutable_name() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.name)
- return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
inline ::std::string* Option::release_name() {
// @@protoc_insertion_point(field_release:google.protobuf.Option.name)
- return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
+}
+inline ::std::string* Option::unsafe_arena_release_name() {
+ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Option.name)
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+
+ return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ GetArenaNoVirtual());
}
inline void Option::set_allocated_name(::std::string* name) {
if (name != NULL) {
@@ -1665,13 +1997,26 @@ inline void Option::set_allocated_name(::std::string* name) {
} else {
}
- name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
+ name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
+ GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.name)
}
+inline void Option::unsafe_arena_set_allocated_name(
+ ::std::string* name) {
+ GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
+ if (name != NULL) {
+
+ } else {
+
+ }
+ name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
+ name, GetArenaNoVirtual());
+ // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Option.name)
+}
// optional .google.protobuf.Any value = 2;
inline bool Option::has_value() const {
- return !_is_default_instance_ && value_ != NULL;
+ return this != internal_default_instance() && value_ != NULL;
}
inline void Option::clear_value() {
if (GetArenaNoVirtual() == NULL && value_ != NULL) delete value_;
@@ -1679,12 +2024,13 @@ inline void Option::clear_value() {
}
inline const ::google::protobuf::Any& Option::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Option.value)
- return value_ != NULL ? *value_ : *default_instance_->value_;
+ return value_ != NULL ? *value_
+ : *::google::protobuf::Any::internal_default_instance();
}
inline ::google::protobuf::Any* Option::mutable_value() {
if (value_ == NULL) {
- value_ = new ::google::protobuf::Any;
+ _slow_mutable_value();
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Option.value)
return value_;
@@ -1692,12 +2038,24 @@ inline ::google::protobuf::Any* Option::mutable_value() {
inline ::google::protobuf::Any* Option::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Option.value)
- ::google::protobuf::Any* temp = value_;
- value_ = NULL;
- return temp;
+ if (GetArenaNoVirtual() != NULL) {
+ return _slow_release_value();
+ } else {
+ ::google::protobuf::Any* temp = value_;
+ value_ = NULL;
+ return temp;
+ }
}
-inline void Option::set_allocated_value(::google::protobuf::Any* value) {
- delete value_;
+inline void Option::set_allocated_value(::google::protobuf::Any* value) {
+ ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
+ if (message_arena == NULL) {
+ delete value_;
+ }
+ if (value != NULL) {
+ if (message_arena != NULL) {
+ message_arena->Own(value);
+ }
+ }
value_ = value;
if (value) {
@@ -1707,6 +2065,9 @@ inline void Option::set_allocated_value(::google::protobuf::Any* value) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.value)
}
+inline const Option* Option::internal_default_instance() {
+ return &Option_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
diff --git a/src/google/protobuf/type.proto b/src/google/protobuf/type.proto
index 1c9cf53d..504cd25d 100644
--- a/src/google/protobuf/type.proto
+++ b/src/google/protobuf/type.proto
@@ -36,10 +36,10 @@ import "google/protobuf/any.proto";
import "google/protobuf/source_context.proto";
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
option java_package = "com.google.protobuf";
option java_outer_classname = "TypeProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// A protocol buffer message type.
diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto
index d5206d24..cc2f4b34 100644
--- a/src/google/protobuf/unittest.proto
+++ b/src/google/protobuf/unittest.proto
@@ -878,3 +878,11 @@ service TestService {
message BarRequest {}
message BarResponse {}
+message TestJsonName {
+ optional int32 field_name1 = 1;
+ optional int32 fieldName2 = 2;
+ optional int32 FieldName3 = 3;
+ optional int32 _field_name4 = 4;
+ optional int32 FIELD_NAME5 = 5;
+ optional int32 field_name6 = 6 [json_name = "@type"];
+}
diff --git a/src/google/protobuf/unknown_field_set.cc b/src/google/protobuf/unknown_field_set.cc
index 8ee99d48..bca3fbf8 100644
--- a/src/google/protobuf/unknown_field_set.cc
+++ b/src/google/protobuf/unknown_field_set.cc
@@ -39,6 +39,7 @@
#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/metadata.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/stl_util.h>
@@ -116,6 +117,12 @@ void UnknownFieldSet::MergeFromAndDestroy(UnknownFieldSet* other) {
other->fields_ = NULL;
}
+void UnknownFieldSet::MergeToInternalMetdata(
+ const UnknownFieldSet& other,
+ internal::InternalMetadataWithArena* metadata) {
+ metadata->mutable_unknown_fields()->MergeFrom(other);
+}
+
int UnknownFieldSet::SpaceUsedExcludingSelf() const {
if (fields_ == NULL) return 0;
diff --git a/src/google/protobuf/unknown_field_set.h b/src/google/protobuf/unknown_field_set.h
index aa752916..c2ad8918 100644
--- a/src/google/protobuf/unknown_field_set.h
+++ b/src/google/protobuf/unknown_field_set.h
@@ -52,6 +52,7 @@ namespace protobuf {
class ZeroCopyInputStream; // zero_copy_stream.h
}
namespace internal {
+ class InternalMetadataWithArena; // metadata.h
class WireFormat; // wire_format.h
class MessageSetFieldSkipperUsingCord;
// extension_set_heavy.cc
@@ -92,6 +93,13 @@ class LIBPROTOBUF_EXPORT UnknownFieldSet {
// Similar to above, but this function will destroy the contents of other.
void MergeFromAndDestroy(UnknownFieldSet* other);
+ // Merge the contents an UnknownFieldSet with the UnknownFieldSet in
+ // *metadata, if there is one. If *metadata doesn't have an UnknownFieldSet
+ // then add one to it and make it be a copy of the first arg.
+ static void MergeToInternalMetdata(
+ const UnknownFieldSet& other,
+ internal::InternalMetadataWithArena* metadata);
+
// Swaps the contents of some other UnknownFieldSet with this one.
inline void Swap(UnknownFieldSet* x);
@@ -175,7 +183,7 @@ class LIBPROTOBUF_EXPORT UnknownField {
TYPE_GROUP
};
- // The field's tag number, as seen on the wire.
+ // The field's field number, as seen on the wire.
inline int number() const;
// The field type.
@@ -204,7 +212,7 @@ class LIBPROTOBUF_EXPORT UnknownField {
void SerializeLengthDelimitedNoTag(io::CodedOutputStream* output) const;
uint8* SerializeLengthDelimitedNoTagToArray(uint8* target) const;
- inline int GetLengthDelimitedSize() const;
+ inline size_t GetLengthDelimitedSize() const;
private:
friend class UnknownFieldSet;
@@ -330,9 +338,9 @@ inline UnknownFieldSet* UnknownField::mutable_group() {
return group_;
}
-inline int UnknownField::GetLengthDelimitedSize() const {
+inline size_t UnknownField::GetLengthDelimitedSize() const {
GOOGLE_DCHECK_EQ(TYPE_LENGTH_DELIMITED, type());
- return static_cast<int>(length_delimited_.string_value_->size());
+ return length_delimited_.string_value_->size();
}
inline void UnknownField::SetType(Type type) {
diff --git a/src/google/protobuf/util/field_comparator.h b/src/google/protobuf/util/field_comparator.h
index 1b4d65b0..3c70a314 100644
--- a/src/google/protobuf/util/field_comparator.h
+++ b/src/google/protobuf/util/field_comparator.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Defines classes for field comparison.
+
// Author: ksroka@google.com (Krzysztof Sroka)
#ifndef GOOGLE_PROTOBUF_UTIL_FIELD_COMPARATOR_H__
@@ -167,7 +169,7 @@ class LIBPROTOBUF_EXPORT DefaultFieldComparator : public FieldComparator {
};
// Defines the map to store the tolerances for floating point comparison.
- typedef map<const FieldDescriptor*, Tolerance> ToleranceMap;
+ typedef std::map<const FieldDescriptor*, Tolerance> ToleranceMap;
// The following methods get executed when CompareFields is called for the
// basic types (instead of submessages). They return true on success. One
diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc
index 409010a0..9dfcbd72 100644
--- a/src/google/protobuf/util/field_mask_util.cc
+++ b/src/google/protobuf/util/field_mask_util.cc
@@ -456,11 +456,12 @@ void FieldMaskTree::TrimMessage(const Node* node, Message* message) {
const int32 field_count = descriptor->field_count();
for (int index = 0; index < field_count; ++index) {
const FieldDescriptor* field = descriptor->field(index);
- if (!ContainsKey(node->children, field->name())) {
+ map<string, Node*>::const_iterator it = node->children.find(field->name());
+ if (it == node->children.end()) {
reflection->ClearField(message, field);
} else {
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
- Node* child = node->children.at(field->name());
+ Node* child = it->second;
if (!child->children.empty()) {
TrimMessage(child, reflection->MutableMessage(message, field));
}
diff --git a/src/google/protobuf/util/field_mask_util.h b/src/google/protobuf/util/field_mask_util.h
index e79b65e9..396c9aea 100644
--- a/src/google/protobuf/util/field_mask_util.h
+++ b/src/google/protobuf/util/field_mask_util.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Defines utilities for the FieldMask well known type.
+
#ifndef GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
#define GOOGLE_PROTOBUF_UTIL_FIELD_MASK_UTIL_H__
diff --git a/src/google/protobuf/util/internal/datapiece.cc b/src/google/protobuf/util/internal/datapiece.cc
index ef8da427..eeb55c6b 100644
--- a/src/google/protobuf/util/internal/datapiece.cc
+++ b/src/google/protobuf/util/internal/datapiece.cc
@@ -259,7 +259,8 @@ StatusOr<string> DataPiece::ToBytes() const {
}
}
-StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type) const {
+StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type,
+ bool use_lower_camel_for_enums) const {
if (type_ == TYPE_NULL) return google::protobuf::NULL_VALUE;
if (type_ == TYPE_STRING) {
@@ -268,20 +269,34 @@ StatusOr<int> DataPiece::ToEnum(const google::protobuf::Enum* enum_type) const {
const google::protobuf::EnumValue* value =
FindEnumValueByNameOrNull(enum_type, enum_name);
if (value != NULL) return value->number();
+
+ // Check if int version of enum is sent as string.
+ StatusOr<int32> int_value = ToInt32();
+ if (int_value.ok()) {
+ if (const google::protobuf::EnumValue* enum_value =
+ FindEnumValueByNumberOrNull(enum_type, int_value.ValueOrDie())) {
+ return enum_value->number();
+ }
+ }
+
// Next try a normalized name.
for (string::iterator it = enum_name.begin(); it != enum_name.end(); ++it) {
*it = *it == '-' ? '_' : ascii_toupper(*it);
}
value = FindEnumValueByNameOrNull(enum_type, enum_name);
if (value != NULL) return value->number();
- } else {
- StatusOr<int32> value = ToInt32();
- if (value.ok()) {
- if (const google::protobuf::EnumValue* enum_value =
- FindEnumValueByNumberOrNull(enum_type, value.ValueOrDie())) {
- return enum_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();
}
+ } else {
+ // We don't need to check whether the value is actually declared in the
+ // enum because we preserve unknown enum values as well.
+ return ToInt32();
}
return InvalidArgument(
ValueAsStringOrDefault("Cannot find enum with given value."));
@@ -354,6 +369,7 @@ bool DataPiece::DecodeBase64(StringPiece src, string* dest) const {
void DataPiece::InternalCopy(const DataPiece& other) {
type_ = other.type_;
+ use_strict_base64_decoding_ = other.use_strict_base64_decoding_;
switch (type_) {
case TYPE_INT32:
case TYPE_INT64:
diff --git a/src/google/protobuf/util/internal/datapiece.h b/src/google/protobuf/util/internal/datapiece.h
index e82cdbac..83516d09 100644
--- a/src/google/protobuf/util/internal/datapiece.h
+++ b/src/google/protobuf/util/internal/datapiece.h
@@ -76,13 +76,22 @@ class LIBPROTOBUF_EXPORT DataPiece {
};
// Constructors and Destructor
- explicit DataPiece(const int32 value) : type_(TYPE_INT32), i32_(value) {}
- explicit DataPiece(const int64 value) : type_(TYPE_INT64), i64_(value) {}
- explicit DataPiece(const uint32 value) : type_(TYPE_UINT32), u32_(value) {}
- explicit DataPiece(const uint64 value) : type_(TYPE_UINT64), u64_(value) {}
- explicit DataPiece(const double value) : type_(TYPE_DOUBLE), double_(value) {}
- explicit DataPiece(const float value) : type_(TYPE_FLOAT), float_(value) {}
- explicit DataPiece(const bool value) : type_(TYPE_BOOL), bool_(value) {}
+ explicit DataPiece(const int32 value)
+ : type_(TYPE_INT32), i32_(value), use_strict_base64_decoding_(false) {}
+ explicit DataPiece(const int64 value)
+ : type_(TYPE_INT64), i64_(value), use_strict_base64_decoding_(false) {}
+ explicit DataPiece(const uint32 value)
+ : type_(TYPE_UINT32), u32_(value), use_strict_base64_decoding_(false) {}
+ explicit DataPiece(const uint64 value)
+ : type_(TYPE_UINT64), u64_(value), use_strict_base64_decoding_(false) {}
+ explicit DataPiece(const double value)
+ : type_(TYPE_DOUBLE),
+ double_(value),
+ use_strict_base64_decoding_(false) {}
+ explicit DataPiece(const float value)
+ : type_(TYPE_FLOAT), float_(value), use_strict_base64_decoding_(false) {}
+ explicit DataPiece(const bool value)
+ : type_(TYPE_BOOL), bool_(value), use_strict_base64_decoding_(false) {}
DataPiece(StringPiece value, bool use_strict_base64_decoding)
: type_(TYPE_STRING),
str_(StringPiecePod::CreateFromStringPiece(value)),
@@ -108,6 +117,8 @@ class LIBPROTOBUF_EXPORT DataPiece {
// Accessors
Type type() const { return type_; }
+ bool use_strict_base64_decoding() { return use_strict_base64_decoding_; }
+
StringPiece str() const {
GOOGLE_LOG_IF(DFATAL, type_ != TYPE_STRING) << "Not a string type.";
return str_;
@@ -148,16 +159,20 @@ class LIBPROTOBUF_EXPORT DataPiece {
// string, first attempts conversion by name, trying names as follows:
// 1) the directly provided string value.
// 2) the value upper-cased and replacing '-' by '_'
+ // 3) if use_lower_camel_for_enums is true it also attempts by comparing
+ // enum name without underscore with the value upper cased above.
// 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) const;
+ util::StatusOr<int> ToEnum(const google::protobuf::Enum* enum_type,
+ bool use_lower_camel_for_enums) const;
private:
// Disallow implicit constructor.
DataPiece();
// Helper to create NULL or ENUM types.
- DataPiece(Type type, int32 val) : type_(type), i32_(val) {}
+ DataPiece(Type type, int32 val)
+ : type_(type), i32_(val), use_strict_base64_decoding_(false) {}
// For numeric conversion between
// int32, int64, uint32, uint64, double, float and bool
diff --git a/src/google/protobuf/util/internal/default_value_objectwriter.cc b/src/google/protobuf/util/internal/default_value_objectwriter.cc
index 1e8dab70..ac1ed9ab 100644
--- a/src/google/protobuf/util/internal/default_value_objectwriter.cc
+++ b/src/google/protobuf/util/internal/default_value_objectwriter.cc
@@ -165,7 +165,10 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::RenderBytes(
if (current_ == NULL) {
ow_->RenderBytes(name, value);
} else {
- RenderDataPiece(name, DataPiece(value, false, true));
+ // Since StringPiece is essentially a pointer, takes a copy of "value" to
+ // avoid ownership issues.
+ string_values_.push_back(new string(value.ToString()));
+ RenderDataPiece(name, DataPiece(*string_values_.back(), false, true));
}
return this;
}
@@ -554,26 +557,29 @@ DefaultValueObjectWriter* DefaultValueObjectWriter::EndList() {
void DefaultValueObjectWriter::RenderDataPiece(StringPiece name,
const DataPiece& data) {
MaybePopulateChildrenOfAny(current_);
- util::StatusOr<string> data_string = data.ToString();
if (current_->type() != NULL && current_->type()->name() == kAnyType &&
- name == "@type" && data_string.ok()) {
- const string& string_value = data_string.ValueOrDie();
- // If the type of current_ is "Any" and its "@type" field is being set here,
- // sets the type of current_ to be the type specified by the "@type".
- util::StatusOr<const google::protobuf::Type*> found_type =
- typeinfo_->ResolveTypeUrl(string_value);
- if (!found_type.ok()) {
- GOOGLE_LOG(WARNING) << "Failed to resolve type '" << string_value << "'.";
- } else {
- current_->set_type(found_type.ValueOrDie());
- }
- current_->set_is_any(true);
- // If the "@type" field is placed after other fields, we should populate
- // 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) {
- current_->PopulateChildren(typeinfo_);
+ name == "@type") {
+ util::StatusOr<string> data_string = data.ToString();
+ if (data_string.ok()) {
+ const string& string_value = data_string.ValueOrDie();
+ // If the type of current_ is "Any" and its "@type" field is being set
+ // here, sets the type of current_ to be the type specified by the
+ // "@type".
+ util::StatusOr<const google::protobuf::Type*> found_type =
+ typeinfo_->ResolveTypeUrl(string_value);
+ if (!found_type.ok()) {
+ GOOGLE_LOG(WARNING) << "Failed to resolve type '" << string_value << "'.";
+ } else {
+ current_->set_type(found_type.ValueOrDie());
+ }
+ current_->set_is_any(true);
+ // If the "@type" field is placed after other fields, we should populate
+ // 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) {
+ current_->PopulateChildren(typeinfo_);
+ }
}
}
Node* child = current_->FindChild(name);
@@ -583,7 +589,6 @@ void DefaultValueObjectWriter::RenderDataPiece(StringPiece name,
new Node(name.ToString(), NULL, PRIMITIVE, data, false,
child == NULL ? current_->path() : child->path(),
suppress_empty_list_, field_scrub_callback_.get()));
- child = node.get();
current_->AddChild(node.release());
} else {
child->set_data(data);
diff --git a/src/google/protobuf/util/internal/error_listener.h b/src/google/protobuf/util/internal/error_listener.h
index 3f063936..1dc814a3 100644
--- a/src/google/protobuf/util/internal/error_listener.h
+++ b/src/google/protobuf/util/internal/error_listener.h
@@ -57,7 +57,7 @@ class LIBPROTOBUF_EXPORT ErrorListener {
// Reports an invalid name at the given location.
virtual void InvalidName(const LocationTrackerInterface& loc,
- StringPiece unknown_name, StringPiece message) = 0;
+ StringPiece invalid_name, StringPiece message) = 0;
// Reports an invalid value for a field.
virtual void InvalidValue(const LocationTrackerInterface& loc,
@@ -82,7 +82,7 @@ class LIBPROTOBUF_EXPORT NoopErrorListener : public ErrorListener {
virtual ~NoopErrorListener() {}
virtual void InvalidName(const LocationTrackerInterface& loc,
- StringPiece unknown_name, StringPiece message) {}
+ StringPiece invalid_name, StringPiece message) {}
virtual void InvalidValue(const LocationTrackerInterface& loc,
StringPiece type_name, StringPiece value) {}
diff --git a/src/google/protobuf/util/internal/json_objectwriter.cc b/src/google/protobuf/util/internal/json_objectwriter.cc
index b84210c1..6e4edd88 100644
--- a/src/google/protobuf/util/internal/json_objectwriter.cc
+++ b/src/google/protobuf/util/internal/json_objectwriter.cc
@@ -147,7 +147,7 @@ JsonObjectWriter* JsonObjectWriter::RenderBytes(StringPiece name,
string base64;
if (use_websafe_base64_for_bytes_)
- WebSafeBase64Escape(value.ToString(), &base64);
+ WebSafeBase64EscapeWithPadding(value.ToString(), &base64);
else
Base64Escape(value, &base64);
@@ -164,19 +164,32 @@ JsonObjectWriter* JsonObjectWriter::RenderNull(StringPiece name) {
return RenderSimple(name, "null");
}
+JsonObjectWriter* JsonObjectWriter::RenderNullAsEmpty(StringPiece name) {
+ return RenderSimple(name, "");
+}
+
void JsonObjectWriter::WritePrefix(StringPiece name) {
bool not_first = !element()->is_first();
if (not_first) WriteChar(',');
if (not_first || !element()->is_root()) NewLine();
- if (!name.empty()) {
+ bool empty_key_ok = GetAndResetEmptyKeyOk();
+ if (!name.empty() || empty_key_ok) {
WriteChar('"');
- ArrayByteSource source(name);
- JsonEscaping::Escape(&source, &sink_);
+ if (!name.empty()) {
+ ArrayByteSource source(name);
+ JsonEscaping::Escape(&source, &sink_);
+ }
stream_->WriteString("\":");
if (!indent_string_.empty()) WriteChar(' ');
}
}
+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 cb7e2fb3..31edc292 100644
--- a/src/google/protobuf/util/internal/json_objectwriter.h
+++ b/src/google/protobuf/util/internal/json_objectwriter.h
@@ -93,7 +93,8 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
stream_(out),
sink_(out),
indent_string_(indent_string.ToString()),
- use_websafe_base64_for_bytes_(false) {}
+ use_websafe_base64_for_bytes_(false),
+ empty_name_ok_for_next_key_(false) {}
virtual ~JsonObjectWriter();
// ObjectWriter methods.
@@ -111,11 +112,19 @@ class LIBPROTOBUF_EXPORT JsonObjectWriter : public StructuredObjectWriter {
virtual JsonObjectWriter* RenderString(StringPiece name, StringPiece value);
virtual JsonObjectWriter* RenderBytes(StringPiece name, StringPiece value);
virtual JsonObjectWriter* RenderNull(StringPiece name);
+ virtual JsonObjectWriter* RenderNullAsEmpty(StringPiece name);
void set_use_websafe_base64_for_bytes(bool value) {
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:
@@ -195,6 +204,10 @@ 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_;
google::protobuf::io::CodedOutputStream* stream_;
ByteSinkWrapper sink_;
@@ -204,6 +217,11 @@ 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 b87b06ac..bbd9d78a 100644
--- a/src/google/protobuf/util/internal/json_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/json_objectwriter_test.cc
@@ -299,11 +299,11 @@ TEST_F(JsonObjectWriterTest, TestWebsafeByteEncoding) {
ow_ = new JsonObjectWriter("", out_stream_);
ow_->set_use_websafe_base64_for_bytes(true);
ow_->StartObject("")
- ->RenderBytes("bytes", "\x03\xef\xc0")
+ ->RenderBytes("bytes", "\x03\xef\xc0\x10")
->EndObject();
// Test that we get websafe base64 encoding when explicitly asked.
- EXPECT_EQ("{\"bytes\":\"A-_A\"}",
+ EXPECT_EQ("{\"bytes\":\"A-_AEA==\"}",
output_.substr(0, out_stream_->ByteCount()));
}
diff --git a/src/google/protobuf/util/internal/json_stream_parser.cc b/src/google/protobuf/util/internal/json_stream_parser.cc
index 39be7b03..a8d48eff 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser.cc
@@ -107,7 +107,8 @@ JsonStreamParser::JsonStreamParser(ObjectWriter* ow)
parsed_storage_(),
string_open_(0),
chunk_storage_(),
- coerce_to_utf8_(false) {
+ coerce_to_utf8_(false),
+ allow_empty_null_(false) {
// Initialize the stack with a single value to be parsed.
stack_.push(VALUE);
}
@@ -277,6 +278,10 @@ util::Status JsonStreamParser::ParseValue(TokenType type) {
case UNKNOWN:
return ReportUnknown("Expected a value.");
default: {
+ if (allow_empty_null_ && IsEmptyNullAllowed(type)) {
+ return ParseEmptyNull();
+ }
+
// Special case for having been cut off while parsing, wait for more data.
// This handles things like 'fals' being at the end of the string, we
// don't know if the next char would be e, completing it, or something
@@ -293,8 +298,8 @@ util::Status JsonStreamParser::ParseString() {
util::Status result = ParseStringHelper();
if (result.ok()) {
ow_->RenderString(key_, parsed_);
- key_.clear();
- parsed_.clear();
+ key_ = StringPiece();
+ parsed_ = StringPiece();
parsed_storage_.clear();
}
return result;
@@ -315,7 +320,6 @@ util::Status JsonStreamParser::ParseStringHelper() {
// We're about to handle an escape, copy all bytes from last to data.
if (last < data) {
parsed_storage_.append(last, data - last);
- last = data;
}
// If we ran out of string after the \, cancel or report an error
// depending on if we expect more data later.
@@ -371,7 +375,6 @@ util::Status JsonStreamParser::ParseStringHelper() {
} else {
if (last < data) {
parsed_storage_.append(last, data - last);
- last = data;
}
parsed_ = StringPiece(parsed_storage_);
}
@@ -471,17 +474,17 @@ util::Status JsonStreamParser::ParseNumber() {
switch (number.type) {
case NumberResult::DOUBLE:
ow_->RenderDouble(key_, number.double_val);
- key_.clear();
+ key_ = StringPiece();
break;
case NumberResult::INT:
ow_->RenderInt64(key_, number.int_val);
- key_.clear();
+ key_ = StringPiece();
break;
case NumberResult::UINT:
ow_->RenderUint64(key_, number.uint_val);
- key_.clear();
+ key_ = StringPiece();
break;
default:
@@ -565,7 +568,7 @@ util::Status JsonStreamParser::HandleBeginObject() {
GOOGLE_DCHECK_EQ('{', *p_.data());
Advance();
ow_->StartObject(key_);
- key_.clear();
+ key_ = StringPiece();
stack_.push(ENTRY);
return util::Status::OK;
}
@@ -615,7 +618,7 @@ util::Status JsonStreamParser::ParseEntry(TokenType type) {
} else {
key_ = parsed_;
}
- parsed_.clear();
+ parsed_ = StringPiece();
}
} else if (type == BEGIN_KEY) {
// Key is a bare key (back compat), create a StringPiece pointing to it.
@@ -648,7 +651,7 @@ util::Status JsonStreamParser::HandleBeginArray() {
GOOGLE_DCHECK_EQ('[', *p_.data());
Advance();
ow_->StartList(key_);
- key_.clear();
+ key_ = StringPiece();
stack_.push(ARRAY_VALUE);
return util::Status::OK;
}
@@ -665,7 +668,8 @@ util::Status JsonStreamParser::ParseArrayValue(TokenType type) {
}
// The ParseValue call may push something onto the stack so we need to make
- // sure an ARRAY_MID is after it, so we push it on now.
+ // sure an ARRAY_MID is after it, so we push it on now. Also, the parsing of
+ // empty-null array value is relying on this ARRAY_MID token.
stack_.push(ARRAY_MID);
util::Status result = ParseValue(type);
if (result == util::Status::CANCELLED) {
@@ -699,25 +703,37 @@ util::Status JsonStreamParser::ParseArrayMid(TokenType type) {
util::Status JsonStreamParser::ParseTrue() {
ow_->RenderBool(key_, true);
- key_.clear();
+ key_ = StringPiece();
p_.remove_prefix(true_len);
return util::Status::OK;
}
util::Status JsonStreamParser::ParseFalse() {
ow_->RenderBool(key_, false);
- key_.clear();
+ key_ = StringPiece();
p_.remove_prefix(false_len);
return util::Status::OK;
}
util::Status JsonStreamParser::ParseNull() {
ow_->RenderNull(key_);
- key_.clear();
+ key_ = StringPiece();
p_.remove_prefix(null_len);
return util::Status::OK;
}
+util::Status JsonStreamParser::ParseEmptyNull() {
+ ow_->RenderNull(key_);
+ key_ = StringPiece();
+ return util::Status::OK;
+}
+
+bool JsonStreamParser::IsEmptyNullAllowed(TokenType type) {
+ if (stack_.empty()) return false;
+ return (stack_.top() == ARRAY_MID && type == VALUE_SEPARATOR) ||
+ stack_.top() == OBJ_MID;
+}
+
util::Status JsonStreamParser::ReportFailure(StringPiece message) {
static const int kContextLength = 20;
const char* p_start = p_.data();
diff --git a/src/google/protobuf/util/internal/json_stream_parser.h b/src/google/protobuf/util/internal/json_stream_parser.h
index 0278c28f..78b35cc2 100644
--- a/src/google/protobuf/util/internal/json_stream_parser.h
+++ b/src/google/protobuf/util/internal/json_stream_parser.h
@@ -179,6 +179,10 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
util::Status ParseTrue();
util::Status ParseFalse();
util::Status ParseNull();
+ util::Status ParseEmptyNull();
+
+ // Whether an empty-null is allowed in the current state.
+ bool IsEmptyNullAllowed(TokenType type);
// Report a failure as a util::Status.
util::Status ReportFailure(StringPiece message);
@@ -247,6 +251,10 @@ class LIBPROTOBUF_EXPORT JsonStreamParser {
// Whether to allow non UTF-8 encoded input and replace invalid code points.
bool coerce_to_utf8_;
+ // Whether allows empty string represented null array value or object entry
+ // value.
+ bool allow_empty_null_;
+
GOOGLE_DISALLOW_IMPLICIT_CONSTRUCTORS(JsonStreamParser);
};
diff --git a/src/google/protobuf/util/internal/json_stream_parser_test.cc b/src/google/protobuf/util/internal/json_stream_parser_test.cc
index 059ea6d8..eaa7e045 100644
--- a/src/google/protobuf/util/internal/json_stream_parser_test.cc
+++ b/src/google/protobuf/util/internal/json_stream_parser_test.cc
@@ -81,12 +81,15 @@ using util::Status;
// For each test we split the input string on every possible character to ensure
// the parser is able to handle arbitrarily split input for all cases. We also
// do a final test of the entire test case one character at a time.
+//
+// It is verified that expected calls to the mocked objects are in sequence.
class JsonStreamParserTest : public ::testing::Test {
protected:
JsonStreamParserTest() : mock_(), ow_(&mock_) {}
virtual ~JsonStreamParserTest() {}
- util::Status RunTest(StringPiece json, int split, bool coerce_utf8 = false) {
+ util::Status RunTest(StringPiece json, int split, bool coerce_utf8 = false,
+ bool allow_empty_null = false) {
JsonStreamParser parser(&mock_);
// Special case for split == length, test parsing one character at a time.
@@ -116,8 +119,10 @@ class JsonStreamParserTest : public ::testing::Test {
return result;
}
- void DoTest(StringPiece json, int split, bool coerce_utf8 = false) {
- util::Status result = RunTest(json, split, coerce_utf8);
+ void DoTest(StringPiece json, int split, bool coerce_utf8 = false,
+ bool allow_empty_null = false) {
+ util::Status result =
+ RunTest(json, split, coerce_utf8, allow_empty_null);
if (!result.ok()) {
GOOGLE_LOG(WARNING) << result;
}
@@ -125,14 +130,21 @@ class JsonStreamParserTest : public ::testing::Test {
}
void DoErrorTest(StringPiece json, int split, StringPiece error_prefix,
- bool coerce_utf8 = false) {
- util::Status result = RunTest(json, split, coerce_utf8);
+ bool coerce_utf8 = false, bool allow_empty_null = false) {
+ util::Status result =
+ RunTest(json, split, coerce_utf8, allow_empty_null);
EXPECT_EQ(util::error::INVALID_ARGUMENT, result.error_code());
StringPiece error_message(result.error_message());
EXPECT_EQ(error_prefix, error_message.substr(0, error_prefix.size()));
}
+#ifndef _MSC_VER
+ // TODO(xiaofeng): We have to disable InSequence check for MSVC because it
+ // causes stack overflow due to its use of a linked list that is desctructed
+ // recursively.
+ ::testing::InSequence in_sequence_;
+#endif // !_MSC_VER
MockObjectWriter mock_;
ExpectingObjectWriter ow_;
};
@@ -308,18 +320,28 @@ TEST_F(JsonStreamParserTest, ObjectKeyTypes) {
}
}
-// - array containing array, object, values (true, false, null, num, string)
-TEST_F(JsonStreamParserTest, ArrayValues) {
+// - array containing primitive values (true, false, null, num, string)
+TEST_F(JsonStreamParserTest, ArrayPrimitiveValues) {
StringPiece str =
- "[true, false, null, 'a string', \"another string\", [22, -127, 45.3, "
- "-1056.4, 11779497823553162765], {'key': true}]";
+ "[true, false, null, 'one', \"two\"]";
for (int i = 0; i <= str.length(); ++i) {
ow_.StartList("")
->RenderBool("", true)
->RenderBool("", false)
->RenderNull("")
- ->RenderString("", "a string")
- ->RenderString("", "another string")
+ ->RenderString("", "one")
+ ->RenderString("", "two")
+ ->EndList();
+ DoTest(str, i);
+ }
+}
+
+// - array containing array, object
+TEST_F(JsonStreamParserTest, ArrayComplexValues) {
+ StringPiece str =
+ "[[22, -127, 45.3, -1056.4, 11779497823553162765], {'key': true}]";
+ for (int i = 0; i <= str.length(); ++i) {
+ ow_.StartList("")
->StartList("")
->RenderUint64("", 22)
->RenderInt64("", -127)
@@ -335,6 +357,7 @@ TEST_F(JsonStreamParserTest, ArrayValues) {
}
}
+
// - object containing array, object, value (true, false, null, num, string)
TEST_F(JsonStreamParserTest, ObjectValues) {
StringPiece str =
diff --git a/src/google/protobuf/util/internal/object_writer.h b/src/google/protobuf/util/internal/object_writer.h
index 5781aa1e..b6fbd19b 100644
--- a/src/google/protobuf/util/internal/object_writer.h
+++ b/src/google/protobuf/util/internal/object_writer.h
@@ -119,6 +119,13 @@ 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 0c38aeb9..4dcf4c3b 100644
--- a/src/google/protobuf/util/internal/proto_writer.cc
+++ b/src/google/protobuf/util/internal/proto_writer.cc
@@ -65,6 +65,7 @@ ProtoWriter::ProtoWriter(TypeResolver* type_resolver,
own_typeinfo_(true),
done_(false),
ignore_unknown_fields_(false),
+ use_lower_camel_for_enums_(false),
element_(NULL),
size_insert_(),
output_(output),
@@ -83,6 +84,7 @@ ProtoWriter::ProtoWriter(const TypeInfo* typeinfo,
own_typeinfo_(false),
done_(false),
ignore_unknown_fields_(false),
+ use_lower_camel_for_enums_(false),
element_(NULL),
size_insert_(),
output_(output),
@@ -264,8 +266,9 @@ inline Status WriteString(int field_number, const DataPiece& data,
// Writes an ENUM field, including tag, to the stream.
inline Status WriteEnum(int field_number, const DataPiece& data,
const google::protobuf::Enum* enum_type,
- CodedOutputStream* stream) {
- StatusOr<int> e = data.ToEnum(enum_type);
+ CodedOutputStream* stream,
+ bool use_lower_camel_for_enums) {
+ StatusOr<int> e = data.ToEnum(enum_type, use_lower_camel_for_enums);
if (e.ok()) {
WireFormatLite::WriteEnum(field_number, e.ValueOrDie(), stream);
}
@@ -662,7 +665,7 @@ ProtoWriter* ProtoWriter::RenderPrimitiveField(
case google::protobuf::Field_Kind_TYPE_ENUM: {
status = WriteEnum(field.number(), data,
typeinfo_->GetEnumByTypeUrl(field.type_url()),
- stream_.get());
+ stream_.get(), use_lower_camel_for_enums_);
break;
}
default: // TYPE_GROUP or TYPE_MESSAGE
diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h
index 7f1108ab..21dff88d 100644
--- a/src/google/protobuf/util/internal/proto_writer.h
+++ b/src/google/protobuf/util/internal/proto_writer.h
@@ -148,6 +148,10 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
ignore_unknown_fields_ = ignore_unknown_fields;
}
+ void set_use_lower_camel_for_enums(bool use_lower_camel_for_enums) {
+ use_lower_camel_for_enums_ = use_lower_camel_for_enums;
+ }
+
protected:
class LIBPROTOBUF_EXPORT ProtoElement : public BaseElement, public LocationTrackerInterface {
public:
@@ -308,6 +312,10 @@ class LIBPROTOBUF_EXPORT ProtoWriter : public StructuredObjectWriter {
// If true, don't report unknown field names to the listener.
bool ignore_unknown_fields_;
+ // If true, check if enum name in camel case or without underscore matches the
+ // field name.
+ bool use_lower_camel_for_enums_;
+
// Variable for internal state processing:
// element_ : the current element.
// size_insert_: sizes of nested messages.
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc
index 0048d75b..df0dbe1b 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource.cc
@@ -288,6 +288,8 @@ StatusOr<uint32> ProtoStreamObjectSource::RenderMap(
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 {
@@ -857,7 +859,8 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
// up.
const google::protobuf::Enum* en =
typeinfo_->GetEnumByTypeUrl(field->type_url());
- // Lookup the name of the enum, and render that. Skips unknown enums.
+ // Lookup the name of the enum, and render that. Unknown enum values
+ // are printed as integers.
if (en != NULL) {
const google::protobuf::EnumValue* enum_value =
FindEnumValueByNumber(*en, buffer32);
@@ -866,9 +869,11 @@ Status ProtoStreamObjectSource::RenderNonMessageField(
ow->RenderString(field_name, ToCamelCase(enum_value->name()));
else
ow->RenderString(field_name, enum_value->name());
+ } else {
+ ow->RenderInt32(field_name, buffer32);
}
} else {
- GOOGLE_LOG(INFO) << "Unknown enum skipped: " << field->type_url();
+ ow->RenderInt32(field_name, buffer32);
}
break;
}
@@ -1019,8 +1024,11 @@ bool ProtoStreamObjectSource::IsMap(
// TODO(xiaofeng): Unify option names.
return field.kind() == google::protobuf::Field_Kind_TYPE_MESSAGE &&
(GetBoolOptionOrDefault(field_type->options(),
- "google.protobuf.MessageOptions.map_entry", false) ||
- GetBoolOptionOrDefault(field_type->options(), "map_entry", false));
+ "google.protobuf.MessageOptions.map_entry",
+ false) ||
+ GetBoolOptionOrDefault(field_type->options(), "map_entry", false) ||
+ GetBoolOptionOrDefault(field_type->options(),
+ "proto2.MessageOptions.map_entry", false));
}
std::pair<int64, int32> ProtoStreamObjectSource::ReadSecondsAndNanos(
@@ -1099,6 +1107,8 @@ const google::protobuf::EnumValue* FindEnumValueByNumber(
// TODO(skarvaje): Look into optimizing this by not doing computation on
// double.
const string FormatNanos(uint32 nanos) {
+ if (nanos == 0) return "";
+
const char* format =
(nanos % 1000 != 0) ? "%.9f" : (nanos % 1000000 != 0) ? "%.6f" : "%.3f";
string formatted =
@@ -1112,3 +1122,4 @@ const string FormatNanos(uint32 nanos) {
} // namespace util
} // namespace protobuf
} // namespace google
+
diff --git a/src/google/protobuf/util/internal/protostream_objectsource.h b/src/google/protobuf/util/internal/protostream_objectsource.h
index 243f85b2..adecfbd3 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource.h
+++ b/src/google/protobuf/util/internal/protostream_objectsource.h
@@ -129,6 +129,28 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
bool include_start_and_end,
ObjectWriter* ow) const;
+ // Renders a repeating field (packed or unpacked). Returns the next tag after
+ // reading all sequential repeating elements. The caller should use this tag
+ // before reading more tags from the stream.
+ virtual util::StatusOr<uint32> RenderList(
+ const google::protobuf::Field* field, StringPiece name, uint32 list_tag,
+ ObjectWriter* ow) const;
+
+ // Looks up a field and verify its consistency with wire type in tag.
+ const google::protobuf::Field* FindAndVerifyField(
+ const google::protobuf::Type& type, uint32 tag) const;
+
+ // Renders a field value to the ObjectWriter.
+ util::Status RenderField(const google::protobuf::Field* field,
+ StringPiece field_name, ObjectWriter* ow) const;
+
+ // Reads field value according to Field spec in 'field' and returns the read
+ // value as string. This only works for primitive datatypes (no message
+ // types).
+ const string ReadFieldValueAsString(
+ const google::protobuf::Field& field) const;
+
+
private:
ProtoStreamObjectSource(google::protobuf::io::CodedInputStream* stream,
const TypeInfo* typeinfo,
@@ -138,19 +160,9 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
const google::protobuf::Type&,
StringPiece, ObjectWriter*);
- // Looks up a field and verify its consistency with wire type in tag.
- const google::protobuf::Field* FindAndVerifyField(
- const google::protobuf::Type& type, uint32 tag) const;
-
// TODO(skarvaje): Mark these methods as non-const as they modify internal
// state (stream_).
//
- // Renders a repeating field (packed or unpacked).
- // Returns the next tag after reading all sequential repeating elements. The
- // caller should use this tag before reading more tags from the stream.
- util::StatusOr<uint32> RenderList(const google::protobuf::Field* field,
- StringPiece name, uint32 list_tag,
- ObjectWriter* ow) const;
// Renders a NWP map.
// Returns the next tag after reading all map entries. The caller should use
// this tag before reading more tags from the stream.
@@ -234,10 +246,6 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
static void DeleteRendererMap();
static TypeRenderer* FindTypeRenderer(const string& type_url);
- // Renders a field value to the ObjectWriter.
- util::Status RenderField(const google::protobuf::Field* field,
- StringPiece field_name, ObjectWriter* ow) const;
-
// Same as above but renders all non-message field types. Callers don't call
// this function directly. They just use RenderField.
util::Status RenderNonMessageField(const google::protobuf::Field* field,
@@ -245,12 +253,6 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
ObjectWriter* ow) const;
- // Reads field value according to Field spec in 'field' and returns the read
- // value as string. This only works for primitive datatypes (no message
- // types).
- const string ReadFieldValueAsString(
- const google::protobuf::Field& field) const;
-
// Utility function to detect proto maps. The 'field' MUST be repeated.
bool IsMap(const google::protobuf::Field& field) const;
@@ -271,6 +273,7 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectSource : public ObjectSource {
// Type information for all the types used in the descriptor. Used to find
// google::protobuf::Type of nested messages/enums.
const TypeInfo* typeinfo_;
+
// Whether this class owns the typeinfo_ object. If true the typeinfo_ object
// should be deleted in the destructor.
bool own_typeinfo_;
diff --git a/src/google/protobuf/util/internal/protostream_objectsource_test.cc b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
index 3f6fdf97..cac28a06 100644
--- a/src/google/protobuf/util/internal/protostream_objectsource_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectsource_test.cc
@@ -42,15 +42,16 @@
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/util/internal/expecting_objectwriter.h>
+#include <google/protobuf/util/internal/testdata/anys.pb.h>
#include <google/protobuf/util/internal/testdata/books.pb.h>
#include <google/protobuf/util/internal/testdata/field_mask.pb.h>
-#include <google/protobuf/util/internal/type_info_test_helper.h>
-#include <google/protobuf/util/internal/constants.h>
-#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/util/internal/testdata/anys.pb.h>
#include <google/protobuf/util/internal/testdata/maps.pb.h>
+#include <google/protobuf/util/internal/testdata/proto3.pb.h>
#include <google/protobuf/util/internal/testdata/struct.pb.h>
#include <google/protobuf/util/internal/testdata/timestamp_duration.pb.h>
+#include <google/protobuf/util/internal/type_info_test_helper.h>
+#include <google/protobuf/util/internal/constants.h>
+#include <google/protobuf/stubs/strutil.h>
#include <gtest/gtest.h>
@@ -66,24 +67,24 @@ using google::protobuf::Message;
using google::protobuf::io::ArrayInputStream;
using google::protobuf::io::CodedInputStream;
using util::Status;
+using google::protobuf::testing::AnyM;
+using google::protobuf::testing::AnyOut;
using google::protobuf::testing::Author;
using google::protobuf::testing::BadAuthor;
using google::protobuf::testing::BadNestedBook;
using google::protobuf::testing::Book;
-using google::protobuf::testing::Cyclic;
using google::protobuf::testing::Book_Label;
+using google::protobuf::testing::Cyclic;
+using google::protobuf::testing::FieldMaskTest;
+using google::protobuf::testing::MapOut;
+using google::protobuf::testing::MapOutWireFormat;
using google::protobuf::testing::NestedBook;
+using google::protobuf::testing::NestedFieldMask;
using google::protobuf::testing::PackedPrimitive;
using google::protobuf::testing::Primitive;
-using google::protobuf::testing::more_author;
-using google::protobuf::testing::maps::MapOut;
-using google::protobuf::testing::maps::MapOutWireFormat;
-using google::protobuf::testing::timestampduration::TimestampDuration;
-using google::protobuf::testing::anys::AnyOut;
-using google::protobuf::testing::anys::AnyM;
-using google::protobuf::testing::FieldMaskTest;
-using google::protobuf::testing::NestedFieldMask;
-using google::protobuf::testing::structs::StructType;
+using google::protobuf::testing::Proto3Message;
+using google::protobuf::testing::StructType;
+using google::protobuf::testing::TimestampDuration;
using ::testing::_;
@@ -101,7 +102,7 @@ class ProtostreamObjectSourceTest
mock_(),
ow_(&mock_),
use_lower_camel_for_enums_(false) {
- helper_.ResetTypeInfo(Book::descriptor());
+ helper_.ResetTypeInfo(Book::descriptor(), Proto3Message::descriptor());
}
virtual ~ProtostreamObjectSourceTest() {}
@@ -493,6 +494,15 @@ TEST_P(ProtostreamObjectSourceTest, EnumCaseIsUnchangedByDefault) {
DoTest(book, Book::descriptor());
}
+TEST_P(ProtostreamObjectSourceTest, UnknownEnum) {
+ Proto3Message message;
+ message.set_enum_value(static_cast<Proto3Message::NestedEnum>(1234));
+ ow_.StartObject("")
+ ->RenderInt32("enumValue", 1234)
+ ->EndObject();
+ DoTest(message, Proto3Message::descriptor());
+}
+
TEST_P(ProtostreamObjectSourceTest, CyclicMessageDepthTest) {
Cyclic cyclic;
cyclic.set_m_int(123);
@@ -679,7 +689,7 @@ INSTANTIATE_TEST_CASE_P(DifferentTypeInfoSourceTest,
// This is the example expected output.
// {
// "any": {
-// "@type": "type.googleapis.com/google.protobuf.testing.anys.AnyM"
+// "@type": "type.googleapis.com/google.protobuf.testing.AnyM"
// "foo": "foovalue"
// }
// }
@@ -694,7 +704,7 @@ TEST_P(ProtostreamObjectSourceAnysTest, BasicAny) {
ow_.StartObject("")
->StartObject("any")
->RenderString("@type",
- "type.googleapis.com/google.protobuf.testing.anys.AnyM")
+ "type.googleapis.com/google.protobuf.testing.AnyM")
->RenderString("foo", "foovalue")
->EndObject()
->EndObject();
@@ -708,8 +718,7 @@ TEST_P(ProtostreamObjectSourceAnysTest, RecursiveAny) {
any->set_type_url("type.googleapis.com/google.protobuf.Any");
::google::protobuf::Any nested_any;
- nested_any.set_type_url(
- "type.googleapis.com/google.protobuf.testing.anys.AnyM");
+ nested_any.set_type_url("type.googleapis.com/google.protobuf.testing.AnyM");
AnyM m;
m.set_foo("foovalue");
@@ -722,7 +731,7 @@ TEST_P(ProtostreamObjectSourceAnysTest, RecursiveAny) {
->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
->StartObject("value")
->RenderString("@type",
- "type.googleapis.com/google.protobuf.testing.anys.AnyM")
+ "type.googleapis.com/google.protobuf.testing.AnyM")
->RenderString("foo", "foovalue")
->EndObject()
->EndObject()
@@ -741,7 +750,7 @@ TEST_P(ProtostreamObjectSourceAnysTest, DoubleRecursiveAny) {
::google::protobuf::Any second_nested_any;
second_nested_any.set_type_url(
- "type.googleapis.com/google.protobuf.testing.anys.AnyM");
+ "type.googleapis.com/google.protobuf.testing.AnyM");
AnyM m;
m.set_foo("foovalue");
@@ -756,7 +765,7 @@ TEST_P(ProtostreamObjectSourceAnysTest, DoubleRecursiveAny) {
->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
->StartObject("value")
->RenderString("@type",
- "type.googleapis.com/google.protobuf.testing.anys.AnyM")
+ "type.googleapis.com/google.protobuf.testing.AnyM")
->RenderString("foo", "foovalue")
->EndObject()
->EndObject()
@@ -1001,6 +1010,19 @@ TEST_P(ProtostreamObjectSourceTimestampTest, InvalidDurationAboveMaxTest) {
EXPECT_EQ(util::error::INTERNAL, status.error_code());
}
+TEST_P(ProtostreamObjectSourceTimestampTest, TimestampDurationDefaultValue) {
+ TimestampDuration out;
+ out.mutable_ts()->set_seconds(0);
+ out.mutable_dur()->set_seconds(0);
+
+ ow_.StartObject("")
+ ->RenderString("ts", "1970-01-01T00:00:00Z")
+ ->RenderString("dur", "0s")
+ ->EndObject();
+
+ DoTest(out, TimestampDuration::descriptor());
+}
+
} // namespace converter
} // namespace util
} // namespace protobuf
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc
index 1825f556..c37e671c 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc
@@ -65,6 +65,7 @@ ProtoStreamObjectWriter::ProtoStreamObjectWriter(
current_(NULL),
options_(options) {
set_ignore_unknown_fields(options_.ignore_unknown_fields);
+ set_use_lower_camel_for_enums(options_.use_lower_camel_for_enums);
}
ProtoStreamObjectWriter::ProtoStreamObjectWriter(
@@ -192,17 +193,11 @@ ProtoStreamObjectWriter::AnyWriter::~AnyWriter() {}
void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) {
++depth_;
// If an object writer is absent, that means we have not called StartAny()
- // before reaching here. This is an invalid state. StartAny() gets called
- // whenever we see an "@type" being rendered (see AnyWriter::RenderDataPiece).
+ // before reaching here, which happens when we have data before the "@type"
+ // field.
if (ow_ == NULL) {
- // Make sure we are not already in an invalid state. This avoids making
- // multiple unnecessary InvalidValue calls.
- if (!invalid_) {
- parent_->InvalidValue("Any",
- StrCat("Missing or invalid @type for any field in ",
- parent_->master_type_.name()));
- invalid_ = true;
- }
+ // 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) {
// For well-known types, the only other field besides "@type" should be a
// "value" field.
@@ -222,10 +217,15 @@ void ProtoStreamObjectWriter::AnyWriter::StartObject(StringPiece name) {
bool ProtoStreamObjectWriter::AnyWriter::EndObject() {
--depth_;
- // As long as depth_ >= 0, we know we haven't reached the end of Any.
- // Propagate these EndObject() calls to the contained ow_. For regular
- // message types, we propagate the end of Any as well.
- if (ow_ != NULL && (depth_ >= 0 || !is_well_known_type_)) {
+ if (ow_ == NULL) {
+ if (depth_ >= 0) {
+ // Save data before the "@type" field for later replay.
+ uninterpreted_events_.push_back(Event(Event::END_OBJECT));
+ }
+ } else if (depth_ >= 0 || !is_well_known_type_) {
+ // As long as depth_ >= 0, we know we haven't reached the end of Any.
+ // Propagate these EndObject() calls to the contained ow_. For regular
+ // message types, we propagate the end of Any as well.
ow_->EndObject();
}
// A negative depth_ implies that we have reached the end of Any
@@ -239,14 +239,9 @@ bool ProtoStreamObjectWriter::AnyWriter::EndObject() {
void ProtoStreamObjectWriter::AnyWriter::StartList(StringPiece name) {
++depth_;
- // We expect ow_ to be present as this call only makes sense inside an Any.
if (ow_ == NULL) {
- if (!invalid_) {
- parent_->InvalidValue("Any",
- StrCat("Missing or invalid @type for any field in ",
- parent_->master_type_.name()));
- invalid_ = true;
- }
+ // 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) {
if (name != "value" && !invalid_) {
parent_->InvalidValue("Any",
@@ -265,8 +260,10 @@ void ProtoStreamObjectWriter::AnyWriter::EndList() {
GOOGLE_LOG(DFATAL) << "Mismatched EndList found, should not be possible";
depth_ = 0;
}
- // We don't write an error on the close, only on the open
- if (ow_ != NULL) {
+ if (ow_ == NULL) {
+ // Save data before the "@type" field for later replay.
+ uninterpreted_events_.push_back(Event(Event::END_LIST));
+ } else {
ow_->EndList();
}
}
@@ -278,12 +275,8 @@ void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece(
if (depth_ == 0 && ow_ == NULL && name == "@type") {
StartAny(value);
} else if (ow_ == NULL) {
- if (!invalid_) {
- parent_->InvalidValue("Any",
- StrCat("Missing or invalid @type for any field in ",
- parent_->master_type_.name()));
- invalid_ = true;
- }
+ // Save data before the "@type" field.
+ uninterpreted_events_.push_back(Event(name, value));
} else if (depth_ == 0 && is_well_known_type_) {
if (name != "value" && !invalid_) {
parent_->InvalidValue("Any",
@@ -293,7 +286,7 @@ void ProtoStreamObjectWriter::AnyWriter::RenderDataPiece(
if (well_known_type_render_ == NULL) {
// 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 (!invalid_) {
+ if (value.type() != DataPiece::TYPE_NULL && !invalid_) {
parent_->InvalidValue("Any", "Expect a JSON object.");
invalid_ = true;
}
@@ -358,13 +351,29 @@ void ProtoStreamObjectWriter::AnyWriter::StartAny(const DataPiece& value) {
if (!is_well_known_type_) {
ow_->StartObject("");
}
+
+ // Now we know the proto type and can interpret all data fields we gathered
+ // before the "@type" field.
+ for (int i = 0; i < uninterpreted_events_.size(); ++i) {
+ uninterpreted_events_[i].Replay(this);
+ }
}
void ProtoStreamObjectWriter::AnyWriter::WriteAny() {
if (ow_ == NULL) {
- // If we had no object writer, we never got any content, so just return
- // immediately, which is equivalent to writing an empty Any.
- return;
+ if (uninterpreted_events_.empty()) {
+ // We never got any content, so just return immediately, which is
+ // equivalent to writing an empty Any.
+ return;
+ } else {
+ // There are uninterpreted data, but we never got a "@type" field.
+ if (!invalid_) {
+ parent_->InvalidValue("Any", StrCat("Missing @type for any field in ",
+ parent_->master_type_.name()));
+ invalid_ = true;
+ }
+ return;
+ }
}
// Render the type_url and value fields directly to the stream.
// type_url has tag 1 and value has tag 2.
@@ -374,6 +383,41 @@ void ProtoStreamObjectWriter::AnyWriter::WriteAny() {
}
}
+void ProtoStreamObjectWriter::AnyWriter::Event::Replay(
+ AnyWriter* writer) const {
+ switch (type_) {
+ case START_OBJECT:
+ writer->StartObject(name_);
+ break;
+ case END_OBJECT:
+ writer->EndObject();
+ break;
+ case START_LIST:
+ writer->StartList(name_);
+ break;
+ case END_LIST:
+ writer->EndList();
+ break;
+ case RENDER_DATA_PIECE:
+ writer->RenderDataPiece(name_, value_);
+ break;
+ }
+}
+
+void ProtoStreamObjectWriter::AnyWriter::Event::DeepCopy() {
+ // DataPiece only contains a string reference. To make sure the referenced
+ // string value stays valid, we make a copy of the string value and update
+ // DataPiece to reference our own copy.
+ if (value_.type() == DataPiece::TYPE_STRING) {
+ value_.str().AppendToString(&value_storage_);
+ value_ = DataPiece(value_storage_, value_.use_strict_base64_decoding());
+ } else if (value_.type() == DataPiece::TYPE_BYTES) {
+ value_storage_ = value_.ToBytes().ValueOrDie();
+ value_ =
+ DataPiece(value_storage_, true, value_.use_strict_base64_decoding());
+ }
+}
+
ProtoStreamObjectWriter::Item::Item(ProtoStreamObjectWriter* enclosing,
ItemType item_type, bool is_placeholder,
bool is_list)
@@ -867,6 +911,7 @@ Status ProtoStreamObjectWriter::RenderStructValue(ProtoStreamObjectWriter* ow,
Status ProtoStreamObjectWriter::RenderTimestamp(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
+ if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for timestamp, value is ",
@@ -897,6 +942,7 @@ static inline util::Status RenderOneFieldPath(ProtoStreamObjectWriter* ow,
Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
+ if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for field mask, value is ",
@@ -907,12 +953,13 @@ Status ProtoStreamObjectWriter::RenderFieldMask(ProtoStreamObjectWriter* ow,
// conversions as much as possible. Because ToSnakeCase sometimes returns the
// wrong value.
google::protobuf::scoped_ptr<ResultCallback1<util::Status, StringPiece> > callback(
- ::google::protobuf::internal::NewPermanentCallback(&RenderOneFieldPath, ow));
+ NewPermanentCallback(&RenderOneFieldPath, ow));
return DecodeCompactFieldMaskPaths(data.str(), callback.get());
}
Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
+ if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
if (data.type() != DataPiece::TYPE_STRING) {
return Status(INVALID_ARGUMENT,
StrCat("Invalid data type for duration, value is ",
@@ -962,6 +1009,7 @@ Status ProtoStreamObjectWriter::RenderDuration(ProtoStreamObjectWriter* ow,
Status ProtoStreamObjectWriter::RenderWrapperType(ProtoStreamObjectWriter* ow,
const DataPiece& data) {
+ if (data.type() == DataPiece::TYPE_NULL) return Status::OK;
ow->ProtoWriter::RenderDataPiece("value", data);
return Status::OK;
}
@@ -1049,13 +1097,18 @@ ProtoStreamObjectWriter* ProtoStreamObjectWriter::RenderDataPiece(
// 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) {
- Push(name, Item::MESSAGE, false, false);
- status = (*type_renderer)(this, data);
- if (!status.ok()) {
- InvalidValue(field->type_url(),
- StrCat("Field '", name, "', ", status.error_message()));
+ // 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 ||
+ field->type_url() == kStructValueTypeUrl) {
+ Push(name, Item::MESSAGE, false, false);
+ status = (*type_renderer)(this, data);
+ if (!status.ok()) {
+ InvalidValue(field->type_url(),
+ StrCat("Field '", name, "', ", status.error_message()));
+ }
+ Pop();
}
- Pop();
return this;
}
@@ -1187,8 +1240,11 @@ bool ProtoStreamObjectWriter::IsMap(const google::protobuf::Field& field) {
// TODO(xiaofeng): Unify option names.
return GetBoolOptionOrDefault(field_type->options(),
- "google.protobuf.MessageOptions.map_entry", false) ||
- GetBoolOptionOrDefault(field_type->options(), "map_entry", false);
+ "google.protobuf.MessageOptions.map_entry",
+ false) ||
+ GetBoolOptionOrDefault(field_type->options(), "map_entry", false) ||
+ GetBoolOptionOrDefault(field_type->options(),
+ "proto2.MessageOptions.map_entry", false);
}
bool ProtoStreamObjectWriter::IsAny(const google::protobuf::Field& field) {
@@ -1213,3 +1269,4 @@ bool ProtoStreamObjectWriter::IsStructListValue(
} // namespace util
} // namespace protobuf
} // namespace google
+
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h
index 2e4d14d1..732971e1 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter.h
+++ b/src/google/protobuf/util/internal/protostream_objectwriter.h
@@ -87,8 +87,14 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// just ignore it and continue to process the rest.
bool ignore_unknown_fields;
+ // If true, check if enum name in camel case or without underscore matches
+ // the field name.
+ bool use_lower_camel_for_enums;
+
Options()
- : struct_integers_as_strings(false), ignore_unknown_fields(false) {}
+ : struct_integers_as_strings(false),
+ ignore_unknown_fields(false),
+ use_lower_camel_for_enums(false) {}
// Default instance of Options with all options set to defaults.
static const Options& Defaults() {
@@ -145,6 +151,57 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
void RenderDataPiece(StringPiece name, const DataPiece& value);
private:
+ // Before the "@type" field is encountered, we store all incoming data
+ // into this Event struct and replay them after we get the "@type" field.
+ class LIBPROTOBUF_EXPORT Event {
+ public:
+ enum Type {
+ START_OBJECT = 0,
+ END_OBJECT = 1,
+ START_LIST = 2,
+ END_LIST = 3,
+ RENDER_DATA_PIECE = 4,
+ };
+
+ // Constructor for END_OBJECT and END_LIST events.
+ explicit Event(Type type) : type_(type), value_(DataPiece::NullData()) {}
+
+ // Constructor for START_OBJECT and START_LIST events.
+ explicit Event(Type type, StringPiece name)
+ : type_(type),
+ name_(name.ToString()),
+ value_(DataPiece::NullData()) {}
+
+ // Constructor for RENDER_DATA_PIECE events.
+ explicit Event(StringPiece name, const DataPiece& value)
+ : type_(RENDER_DATA_PIECE), name_(name.ToString()), value_(value) {
+ DeepCopy();
+ }
+
+ Event(const Event& other)
+ : type_(other.type_), name_(other.name_), value_(other.value_) {
+ DeepCopy();
+ }
+
+ Event& operator=(const Event& other) {
+ type_ = other.type_;
+ name_ = other.name_;
+ value_ = other.value_;
+ DeepCopy();
+ return *this;
+ }
+
+ void Replay(AnyWriter* writer) const;
+
+ private:
+ void DeepCopy();
+
+ Type type_;
+ string name_;
+ DataPiece value_;
+ string value_storage_;
+ };
+
// Handles starting up the any once we have a type.
void StartAny(const DataPiece& value);
@@ -180,6 +237,9 @@ class LIBPROTOBUF_EXPORT ProtoStreamObjectWriter : public ProtoWriter {
// }
bool is_well_known_type_;
TypeRenderer* well_known_type_render_;
+
+ // Store data before the "@type" field.
+ std::vector<Event> uninterpreted_events_;
};
// Represents an item in a stack of items used to keep state between
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
index 30e58e62..e7b38520 100644
--- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
+++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc
@@ -41,18 +41,20 @@
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/message.h>
#include <google/protobuf/util/internal/mock_error_listener.h>
+#include <google/protobuf/util/internal/testdata/anys.pb.h>
#include <google/protobuf/util/internal/testdata/books.pb.h>
#include <google/protobuf/util/internal/testdata/field_mask.pb.h>
+#include <google/protobuf/util/internal/testdata/maps.pb.h>
+#include <google/protobuf/util/internal/testdata/oneofs.pb.h>
+#include <google/protobuf/util/internal/testdata/proto3.pb.h>
+#include <google/protobuf/util/internal/testdata/struct.pb.h>
+#include <google/protobuf/util/internal/testdata/timestamp_duration.pb.h>
+#include <google/protobuf/util/internal/testdata/wrappers.pb.h>
#include <google/protobuf/util/internal/type_info_test_helper.h>
#include <google/protobuf/util/internal/constants.h>
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/stubs/bytestream.h>
#include <google/protobuf/stubs/strutil.h>
-#include <google/protobuf/util/internal/testdata/anys.pb.h>
-#include <google/protobuf/util/internal/testdata/maps.pb.h>
-#include <google/protobuf/util/internal/testdata/oneofs.pb.h>
-#include <google/protobuf/util/internal/testdata/struct.pb.h>
-#include <google/protobuf/util/internal/testdata/timestamp_duration.pb.h>
#include <gtest/gtest.h>
@@ -61,27 +63,28 @@ namespace protobuf {
namespace util {
namespace converter {
+using google::protobuf::testing::AnyM;
+using google::protobuf::testing::AnyOut;
using google::protobuf::testing::Author;
using google::protobuf::testing::Book;
-using google::protobuf::testing::Book_Data;
+using google::protobuf::testing::FieldMaskTest;
+using google::protobuf::testing::Int32Wrapper;
+using google::protobuf::testing::MapIn;
using google::protobuf::testing::Primitive;
+using google::protobuf::testing::Proto3Message;
using google::protobuf::testing::Publisher;
+using google::protobuf::testing::StructType;
+using google::protobuf::testing::TimestampDuration;
+using google::protobuf::testing::ValueWrapper;
+using google::protobuf::testing::oneofs::OneOfsRequest;
using google::protobuf::Descriptor;
using google::protobuf::DescriptorPool;
using google::protobuf::DynamicMessageFactory;
using google::protobuf::FileDescriptorProto;
using google::protobuf::Message;
-using google::protobuf::io::ArrayInputStream;
using strings::GrowingArrayByteSink;
using ::testing::_;
using ::testing::Args;
-using google::protobuf::testing::anys::AnyM;
-using google::protobuf::testing::anys::AnyOut;
-using google::protobuf::testing::oneofs::OneOfsRequest;
-using google::protobuf::testing::FieldMaskTest;
-using google::protobuf::testing::maps::MapIn;
-using google::protobuf::testing::structs::StructType;
-using google::protobuf::testing::timestampduration::TimestampDuration;
namespace {
@@ -268,6 +271,84 @@ TEST_P(ProtoStreamObjectWriterTest, CustomJsonName) {
CheckOutput(book);
}
+TEST_P(ProtoStreamObjectWriterTest, IntEnumValuesAreAccepted) {
+ Book book;
+ book.set_title("Some Book");
+ book.set_type(google::protobuf::testing::Book_Type_KIDS);
+ Author* robert = book.mutable_author();
+ robert->set_name("robert");
+
+ ow_->StartObject("")
+ ->RenderString("title", "Some Book")
+ ->RenderString("type", "2")
+ ->StartObject("author")
+ ->RenderString("name", "robert")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(book);
+}
+
+TEST_P(ProtoStreamObjectWriterTest, EnumValuesWithoutUnderscoreAreAccepted) {
+ Book book;
+ book.set_title("Some Book");
+ book.set_type(google::protobuf::testing::Book_Type_ACTION_AND_ADVENTURE);
+ Author* robert = book.mutable_author();
+ robert->set_name("robert");
+
+ options_.use_lower_camel_for_enums = true;
+ ResetProtoWriter();
+
+ ow_->StartObject("")
+ ->RenderString("title", "Some Book")
+ ->RenderString("type", "ACTIONANDADVENTURE")
+ ->StartObject("author")
+ ->RenderString("name", "robert")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(book);
+}
+
+TEST_P(ProtoStreamObjectWriterTest, EnumValuesInCamelCaseAreAccepted) {
+ Book book;
+ book.set_title("Some Book");
+ book.set_type(google::protobuf::testing::Book_Type_ACTION_AND_ADVENTURE);
+ Author* robert = book.mutable_author();
+ robert->set_name("robert");
+
+ options_.use_lower_camel_for_enums = true;
+ ResetProtoWriter();
+
+ ow_->StartObject("")
+ ->RenderString("title", "Some Book")
+ ->RenderString("type", "actionAndAdventure")
+ ->StartObject("author")
+ ->RenderString("name", "robert")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(book);
+}
+
+TEST_P(ProtoStreamObjectWriterTest,
+ EnumValuesInCamelCaseWithNameNotUppercaseAreAccepted) {
+ Book book;
+ book.set_title("Some Book");
+ book.set_type(google::protobuf::testing::Book_Type_arts_and_photography);
+ Author* robert = book.mutable_author();
+ robert->set_name("robert");
+
+ options_.use_lower_camel_for_enums = true;
+ ResetProtoWriter();
+
+ ow_->StartObject("")
+ ->RenderString("title", "Some Book")
+ ->RenderString("type", "artsAndPhotography")
+ ->StartObject("author")
+ ->RenderString("name", "robert")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(book);
+}
+
TEST_P(ProtoStreamObjectWriterTest, PrimitiveFromStringConversion) {
Primitive full;
full.set_fix32(101);
@@ -826,6 +907,19 @@ TEST_P(ProtoStreamObjectWriterTest, IgnoreUnknownListAtPublisher) {
CheckOutput(expected);
}
+TEST_P(ProtoStreamObjectWriterTest, AcceptUnknownEnumValue) {
+ ResetTypeInfo(Proto3Message::descriptor());
+
+ Proto3Message expected;
+ expected.set_enum_value(static_cast<Proto3Message::NestedEnum>(12345));
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")
+ ->RenderInt32("enumValue", 12345)
+ ->EndObject();
+ CheckOutput(expected);
+}
+
TEST_P(ProtoStreamObjectWriterTest, MissingRequiredField) {
Book expected;
expected.set_title("My Title");
@@ -1338,9 +1432,9 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest,
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.Timestamp"),
StringPiece(
- "Field 'ts', Invalid data type for timestamp, value is null")))
+ "Field 'ts', Invalid data type for timestamp, value is 1")))
.With(Args<0>(HasObjectLocation("ts")));
- ow_->StartObject("")->RenderNull("ts")->EndObject();
+ ow_->StartObject("")->RenderInt32("ts", 1)->EndObject();
CheckOutput(timestamp);
}
@@ -1352,8 +1446,22 @@ TEST_P(ProtoStreamObjectWriterTimestampDurationTest,
InvalidValue(
_, StringPiece("type.googleapis.com/google.protobuf.Duration"),
StringPiece(
- "Field 'dur', Invalid data type for duration, value is null")))
+ "Field 'dur', Invalid data type for duration, value is 1")))
.With(Args<0>(HasObjectLocation("dur")));
+ ow_->StartObject("")->RenderInt32("dur", 1)->EndObject();
+ CheckOutput(duration);
+}
+
+TEST_P(ProtoStreamObjectWriterTimestampDurationTest, TimestampAcceptsNull) {
+ TimestampDuration timestamp;
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")->RenderNull("ts")->EndObject();
+ CheckOutput(timestamp);
+}
+
+TEST_P(ProtoStreamObjectWriterTimestampDurationTest, DurationAcceptsNull) {
+ TimestampDuration duration;
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
ow_->StartObject("")->RenderNull("dur")->EndObject();
CheckOutput(duration);
}
@@ -1415,6 +1523,28 @@ TEST_P(ProtoStreamObjectWriterStructTest, StructInvalidInputFailure) {
CheckOutput(struct_type);
}
+TEST_P(ProtoStreamObjectWriterStructTest, StructAcceptsNull) {
+ StructType struct_type;
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+
+ ow_->StartObject("")->RenderNull("object")->EndObject();
+ CheckOutput(struct_type);
+}
+
+TEST_P(ProtoStreamObjectWriterStructTest, StructValuePreservesNull) {
+ StructType struct_type;
+ (*struct_type.mutable_object()->mutable_fields())["key"].set_null_value(
+ google::protobuf::NULL_VALUE);
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+
+ ow_->StartObject("")
+ ->StartObject("object")
+ ->RenderNull("key")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(struct_type);
+}
+
TEST_P(ProtoStreamObjectWriterStructTest, SimpleRepeatedStructMapKeyTest) {
EXPECT_CALL(
listener_,
@@ -1482,6 +1612,15 @@ TEST_P(ProtoStreamObjectWriterStructTest, OptionStructIntAsStringsTest) {
CheckOutput(struct_type);
}
+TEST_P(ProtoStreamObjectWriterStructTest, ValuePreservesNull) {
+ ValueWrapper value;
+ value.mutable_value()->set_null_value(google::protobuf::NULL_VALUE);
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")->RenderNull("value")->EndObject();
+ CheckOutput(value);
+}
+
class ProtoStreamObjectWriterMapTest : public BaseProtoStreamObjectWriterTest {
protected:
ProtoStreamObjectWriterMapTest()
@@ -1527,11 +1666,14 @@ class ProtoStreamObjectWriterAnyTest : public BaseProtoStreamObjectWriterTest {
ProtoStreamObjectWriterAnyTest() {
vector<const Descriptor*> descriptors;
descriptors.push_back(AnyOut::descriptor());
+ descriptors.push_back(Book::descriptor());
+ descriptors.push_back(google::protobuf::Any::descriptor());
descriptors.push_back(google::protobuf::DoubleValue::descriptor());
+ descriptors.push_back(google::protobuf::FieldMask::descriptor());
+ descriptors.push_back(google::protobuf::Int32Value::descriptor());
+ descriptors.push_back(google::protobuf::Struct::descriptor());
descriptors.push_back(google::protobuf::Timestamp::descriptor());
- descriptors.push_back(google::protobuf::Any::descriptor());
descriptors.push_back(google::protobuf::Value::descriptor());
- descriptors.push_back(google::protobuf::Struct::descriptor());
ResetTypeInfo(descriptors);
}
};
@@ -1564,8 +1706,7 @@ TEST_P(ProtoStreamObjectWriterAnyTest, RecursiveAny) {
any->set_type_url("type.googleapis.com/google.protobuf.Any");
::google::protobuf::Any nested_any;
- nested_any.set_type_url(
- "type.googleapis.com/google.protobuf.testing.anys.AnyM");
+ nested_any.set_type_url("type.googleapis.com/google.protobuf.testing.AnyM");
AnyM m;
m.set_foo("foovalue");
@@ -1578,11 +1719,12 @@ TEST_P(ProtoStreamObjectWriterAnyTest, RecursiveAny) {
->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
->StartObject("value")
->RenderString("@type",
- "type.googleapis.com/google.protobuf.testing.anys.AnyM")
+ "type.googleapis.com/google.protobuf.testing.AnyM")
->RenderString("foo", "foovalue")
->EndObject()
->EndObject()
->EndObject();
+ CheckOutput(out, 107);
}
TEST_P(ProtoStreamObjectWriterAnyTest, DoubleRecursiveAny) {
@@ -1595,7 +1737,7 @@ TEST_P(ProtoStreamObjectWriterAnyTest, DoubleRecursiveAny) {
::google::protobuf::Any second_nested_any;
second_nested_any.set_type_url(
- "type.googleapis.com/google.protobuf.testing.anys.AnyM");
+ "type.googleapis.com/google.protobuf.testing.AnyM");
AnyM m;
m.set_foo("foovalue");
@@ -1611,18 +1753,110 @@ TEST_P(ProtoStreamObjectWriterAnyTest, DoubleRecursiveAny) {
->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
->StartObject("value")
->RenderString("@type",
- "type.googleapis.com/google.protobuf.testing.anys.AnyM")
+ "type.googleapis.com/google.protobuf.testing.AnyM")
->RenderString("foo", "foovalue")
->EndObject()
->EndObject()
->EndObject()
->EndObject();
+ CheckOutput(out, 151);
+}
+
+TEST_P(ProtoStreamObjectWriterAnyTest, TypeUrlAtEnd) {
+ Book book;
+ book.set_title("C++");
+ book.set_length(1234);
+ book.set_content("Hello World!");
+
+ ::google::protobuf::Any any;
+ any.PackFrom(book);
+
+ ::google::protobuf::Any outer_any;
+ outer_any.PackFrom(any);
+
+ AnyOut out;
+ out.mutable_any()->PackFrom(outer_any);
+
+ // Put the @type field at the end of each Any message. Parsers should
+ // be able to accept that.
+ ow_->StartObject("")
+ ->StartObject("any")
+ ->StartObject("value")
+ ->StartObject("value")
+ ->RenderString("title", "C++")
+ ->RenderInt32("length", 1234)
+ ->RenderBytes("content", "Hello World!")
+ ->RenderString("@type",
+ "type.googleapis.com/google.protobuf.testing.Book")
+ ->EndObject()
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
+ ->EndObject()
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(out);
+}
+
+// Same as TypeUrlAtEnd, but use temporary string values to make sure we don't
+// mistakenly store StringPiece objects pointing to invalid memory.
+TEST_P(ProtoStreamObjectWriterAnyTest, TypeUrlAtEndWithTemporaryStrings) {
+ Book book;
+ book.set_title("C++");
+ book.set_length(1234);
+ book.set_content("Hello World!");
+
+ ::google::protobuf::Any any;
+ any.PackFrom(book);
+
+ ::google::protobuf::Any outer_any;
+ outer_any.PackFrom(any);
+
+ AnyOut out;
+ out.mutable_any()->PackFrom(outer_any);
+
+ string name, value;
+ // Put the @type field at the end of each Any message. Parsers should
+ // be able to accept that.
+ ow_->StartObject("")->StartObject("any");
+ {
+ ow_->StartObject("value");
+ {
+ ow_->StartObject("value");
+ {
+ name = "title";
+ value = "C++";
+ ow_->RenderString(name, value);
+ name = "length";
+ ow_->RenderInt32(name, 1234);
+ name = "content";
+ value = "Hello World!";
+ ow_->RenderBytes(name, value);
+ name = "@type";
+ value = "type.googleapis.com/google.protobuf.testing.Book";
+ ow_->RenderString(name, value);
+ }
+ ow_->EndObject();
+
+ name = "@type";
+ value = "type.googleapis.com/google.protobuf.Any";
+ ow_->RenderString(name, value);
+ }
+ ow_->EndObject();
+
+ name = "@type";
+ value = "type.googleapis.com/google.protobuf.Any";
+ ow_->RenderString(name, value);
+ }
+ ow_->EndObject()->EndObject();
+ CheckOutput(out);
}
TEST_P(ProtoStreamObjectWriterAnyTest, EmptyAnyFromEmptyObject) {
AnyOut out;
out.mutable_any();
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+
ow_->StartObject("")->StartObject("any")->EndObject()->EndObject();
CheckOutput(out, 2);
@@ -1631,11 +1865,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, EmptyAnyFromEmptyObject) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails1) {
AnyOut any;
- EXPECT_CALL(
- listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Missing or invalid @type for any field in "
- "google.protobuf.testing.anys.AnyOut")));
+ EXPECT_CALL(listener_,
+ InvalidValue(_, StringPiece("Any"),
+ StringPiece("Missing @type for any field in "
+ "google.protobuf.testing.AnyOut")));
ow_->StartObject("")
->StartObject("any")
@@ -1649,11 +1882,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails1) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails2) {
AnyOut any;
- EXPECT_CALL(
- listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Missing or invalid @type for any field in "
- "google.protobuf.testing.anys.AnyOut")));
+ EXPECT_CALL(listener_,
+ InvalidValue(_, StringPiece("Any"),
+ StringPiece("Missing @type for any field in "
+ "google.protobuf.testing.AnyOut")));
ow_->StartObject("")
->StartObject("any")
@@ -1667,11 +1899,10 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails2) {
TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithoutTypeUrlFails3) {
AnyOut any;
- EXPECT_CALL(
- listener_,
- InvalidValue(_, StringPiece("Any"),
- StringPiece("Missing or invalid @type for any field in "
- "google.protobuf.testing.anys.AnyOut")));
+ EXPECT_CALL(listener_,
+ InvalidValue(_, StringPiece("Any"),
+ StringPiece("Missing @type for any field in "
+ "google.protobuf.testing.AnyOut")));
ow_->StartObject("")
->StartObject("any")
@@ -1716,9 +1947,21 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWithUnknownTypeFails) {
CheckOutput(any);
}
-TEST_P(ProtoStreamObjectWriterAnyTest, AnyNullInputFails) {
+TEST_P(ProtoStreamObjectWriterAnyTest, AnyIncorrectInputTypeFails) {
+ AnyOut any;
+
+ EXPECT_CALL(
+ listener_,
+ InvalidValue(_, StringPiece("type.googleapis.com/google.protobuf.Any"),
+ StringPiece("1")));
+ ow_->StartObject("")->RenderInt32("any", 1)->EndObject();
+ CheckOutput(any);
+}
+
+TEST_P(ProtoStreamObjectWriterAnyTest, AnyAcceptsNull) {
AnyOut any;
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
ow_->StartObject("")->RenderNull("any")->EndObject();
CheckOutput(any);
}
@@ -1956,6 +2199,111 @@ TEST_P(ProtoStreamObjectWriterAnyTest, AnyWellKnownTypesExpectObjectForAny) {
CheckOutput(any);
}
+// {
+// "any": {
+// "@type": "type.googleapis.com/google.protobuf.Any",
+// "value": null
+// }
+// }
+TEST_P(ProtoStreamObjectWriterAnyTest, AnyInAnyAcceptsNull) {
+ AnyOut out;
+ google::protobuf::Any empty;
+ out.mutable_any()->PackFrom(empty);
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.Any")
+ ->RenderNull("value")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(out);
+}
+
+// {
+// "any": {
+// "@type": "type.googleapis.com/google.protobuf.Timestamp",
+// "value": null
+// }
+// }
+TEST_P(ProtoStreamObjectWriterAnyTest, TimestampInAnyAcceptsNull) {
+ AnyOut out;
+ google::protobuf::Timestamp empty;
+ out.mutable_any()->PackFrom(empty);
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.Timestamp")
+ ->RenderNull("value")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(out);
+}
+
+// {
+// "any": {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": null
+// }
+// }
+TEST_P(ProtoStreamObjectWriterAnyTest, DurationInAnyAcceptsNull) {
+ AnyOut out;
+ google::protobuf::Duration empty;
+ out.mutable_any()->PackFrom(empty);
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.Duration")
+ ->RenderNull("value")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(out);
+}
+
+// {
+// "any": {
+// "@type": "type.googleapis.com/google.protobuf.FieldMask",
+// "value": null
+// }
+// }
+TEST_P(ProtoStreamObjectWriterAnyTest, FieldMaskInAnyAcceptsNull) {
+ AnyOut out;
+ google::protobuf::FieldMask empty;
+ out.mutable_any()->PackFrom(empty);
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.FieldMask")
+ ->RenderNull("value")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(out);
+}
+
+// {
+// "any": {
+// "@type": "type.googleapis.com/google.protobuf.Int32Value",
+// "value": null
+// }
+// }
+TEST_P(ProtoStreamObjectWriterAnyTest, WrapperInAnyAcceptsNull) {
+ AnyOut out;
+ google::protobuf::Int32Value empty;
+ out.mutable_any()->PackFrom(empty);
+
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")
+ ->StartObject("any")
+ ->RenderString("@type", "type.googleapis.com/google.protobuf.Int32Value")
+ ->RenderNull("value")
+ ->EndObject()
+ ->EndObject();
+ CheckOutput(out);
+}
+
class ProtoStreamObjectWriterFieldMaskTest
: public BaseProtoStreamObjectWriterTest {
protected:
@@ -2201,6 +2549,36 @@ TEST_P(ProtoStreamObjectWriterFieldMaskTest, MapKeyCanContainAnyChars) {
CheckOutput(expected);
}
+TEST_P(ProtoStreamObjectWriterFieldMaskTest, FieldMaskAcceptsNull) {
+ FieldMaskTest expected;
+ EXPECT_CALL(listener_, InvalidValue(_, _, _)).Times(0);
+ ow_->StartObject("")->RenderNull("single_mask")->EndObject();
+ CheckOutput(expected);
+}
+
+class ProtoStreamObjectWriterWrappersTest
+ : public BaseProtoStreamObjectWriterTest {
+ protected:
+ ProtoStreamObjectWriterWrappersTest() {
+ vector<const Descriptor*> descriptors;
+ descriptors.push_back(Int32Wrapper::descriptor());
+ descriptors.push_back(google::protobuf::Int32Value::descriptor());
+ ResetTypeInfo(descriptors);
+ }
+};
+
+INSTANTIATE_TEST_CASE_P(DifferentTypeInfoSourceTest,
+ ProtoStreamObjectWriterWrappersTest,
+ ::testing::Values(
+ testing::USE_TYPE_RESOLVER));
+
+TEST_P(ProtoStreamObjectWriterWrappersTest, WrapperAcceptsNull) {
+ Int32Wrapper wrapper;
+ EXPECT_CALL(listener_, InvalidName(_, _, _)).Times(0);
+ ow_->StartObject("")->RenderNull("int32")->EndObject();
+ CheckOutput(wrapper);
+}
+
class ProtoStreamObjectWriterOneOfsTest
: public BaseProtoStreamObjectWriterTest {
protected:
@@ -2368,7 +2746,6 @@ TEST_P(ProtoStreamObjectWriterOneOfsTest,
StringPiece("oneof field 'data' is already set. "
"Cannot set 'intData'")));
- using google::protobuf::testing::oneofs::OneOfsRequest;
// JSON:
// { "anyData":
// { "@type":
diff --git a/src/google/protobuf/util/internal/testdata/anys.proto b/src/google/protobuf/util/internal/testdata/anys.proto
index 18c59cbb..a9ebca3d 100644
--- a/src/google/protobuf/util/internal/testdata/anys.proto
+++ b/src/google/protobuf/util/internal/testdata/anys.proto
@@ -28,16 +28,75 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Proto to test Proto3 Any serialization.
syntax = "proto3";
-package google.protobuf.testing.anys;
-option java_package = "com.google.protobuf.testing.anys";
+package google.protobuf.testing;
import "google/protobuf/any.proto";
+import "google/protobuf/struct.proto";
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/wrappers.proto";
+
+// Top-level test cases proto used by MarshallingTest. See description
+// at the top of the class MarshallingTest for details on how to write
+// test cases.
+message AnyTestCases {
+ AnyWrapper empty_any = 1;
+ AnyWrapper type_only_any = 2;
+ AnyWrapper wrapper_any = 3;
+ AnyWrapper any_with_timestamp_value = 4;
+ AnyWrapper any_with_duration_value = 5;
+ AnyWrapper any_with_struct_value = 6;
+ AnyWrapper recursive_any = 7;
+ AnyWrapper any_with_message_value = 8;
+ AnyWrapper any_with_nested_message = 9;
+ AnyWrapper any_with_message_with_wrapper_type = 10;
+ AnyWrapper any_with_message_with_timestamp = 11;
+ AnyWrapper any_with_message_containing_map = 12;
+ AnyWrapper any_with_message_containing_struct = 13;
+ AnyWrapper any_with_message_containing_repeated_message = 14;
+ AnyWrapper recursive_any_with_type_field_at_end = 15;
+
+ google.protobuf.Any top_level_any = 50;
+ google.protobuf.Any top_level_any_with_type_field_at_end = 51;
+}
+
+message AnyWrapper {
+ google.protobuf.Any any = 1;
+}
+
+// Hack to make sure the types we put into the any are included in the types.
+// Real solution is to add these types to the service config.
+message Imports {
+ google.protobuf.DoubleValue dbl = 1;
+ google.protobuf.Struct struct = 2;
+ google.protobuf.Timestamp timestamp = 3;
+ google.protobuf.Duration duration = 4;
+ google.protobuf.Int32Value i32 = 5;
+ Data data = 100;
+}
+
+message Data {
+ int32 attr = 1;
+ string str = 2;
+ repeated string msgs = 3;
+ Data nested_data = 4;
+ google.protobuf.Int32Value int_wrapper = 5;
+ google.protobuf.Timestamp time = 6;
+ map<string, string> map_data = 7;
+ google.protobuf.Struct struct_data = 8;
+ repeated Data repeated_data = 9;
+}
+
+service AnyTestService {
+ rpc Call(AnyTestCases) returns (AnyTestCases);
+ rpc Call1(Imports) returns (Imports);
+}
message AnyIn {
string something = 1;
+ google.protobuf.Any any = 2;
}
message AnyOut {
@@ -47,7 +106,3 @@ message AnyOut {
message AnyM {
string foo = 1;
}
-
-service TestService {
- rpc Call(AnyIn) returns (AnyOut);
-}
diff --git a/src/google/protobuf/util/internal/testdata/books.proto b/src/google/protobuf/util/internal/testdata/books.proto
index 1cbbba47..9fe4f7aa 100644
--- a/src/google/protobuf/util/internal/testdata/books.proto
+++ b/src/google/protobuf/util/internal/testdata/books.proto
@@ -31,6 +31,10 @@
// Author: sven@google.com (Sven Mawson)
//
// Sample protos for testing.
+
+// Some of the older enums don't use CAPITALS_WITH_UNDERSCORES for testing.
+// LINT: LEGACY_NAMES
+
syntax = "proto2";
package google.protobuf.testing;
@@ -60,6 +64,7 @@ message Book {
FICTION = 1;
KIDS = 2;
ACTION_AND_ADVENTURE = 3;
+ arts_and_photography = 4;
}
optional Type type = 11;
diff --git a/src/google/protobuf/util/internal/testdata/maps.proto b/src/google/protobuf/util/internal/testdata/maps.proto
index 6475ecdd..0f381b32 100644
--- a/src/google/protobuf/util/internal/testdata/maps.proto
+++ b/src/google/protobuf/util/internal/testdata/maps.proto
@@ -28,11 +28,76 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Proto to test proto3 maps.
syntax = "proto3";
-package google.protobuf.testing.maps;
-option java_package = "com.google.protobuf.testing.maps";
+package google.protobuf.testing;
+
+// Top-level test cases proto used by MarshallingTest. See description
+// at the top of the class MarshallingTest for details on how to write
+// test cases.
+message MapsTestCases {
+ EmptyMap empty_map = 1;
+ StringtoInt string_to_int = 2;
+ IntToString int_to_string = 3;
+ Mixed1 mixed1 = 4;
+ Mixed2 mixed2 = 5;
+ MapOfObjects map_of_objects = 6;
+
+ // Empty key tests
+ StringtoInt empty_key_string_to_int1 = 7;
+ StringtoInt empty_key_string_to_int2 = 8;
+ StringtoInt empty_key_string_to_int3 = 9;
+ BoolToString empty_key_bool_to_string = 10;
+ IntToString empty_key_int_to_string = 11;
+ Mixed1 empty_key_mixed = 12;
+ MapOfObjects empty_key_map_objects = 13;
+}
+
+message EmptyMap {
+ map<int32, int32> map = 1;
+}
+
+message StringtoInt {
+ map<string, int32> map = 1;
+}
+
+message IntToString {
+ map<int32, string> map = 1;
+}
+
+message BoolToString {
+ map<bool, string> map = 1;
+}
+
+message Mixed1 {
+ string msg = 1;
+ map<string, float> map = 2;
+}
+
+message Mixed2 {
+ enum E {
+ E0 = 0;
+ E1 = 1;
+ E2 = 2;
+ E3 = 3;
+ }
+ map<int32, bool> map = 1;
+ E ee = 2;
+}
+
+message MapOfObjects {
+ message M {
+ string inner_text = 1;
+ }
+ map<string, M> map = 1;
+}
+
+message DummyRequest {
+}
+
+service MapsTestService {
+ rpc Call(DummyRequest) returns (MapsTestCases);
+}
message MapIn {
string other = 1;
@@ -79,8 +144,3 @@ message MapOutWireFormat {
message MapM {
string foo = 1;
}
-
-service TestService {
- rpc Call1(MapIn) returns (MapOut);
- rpc Call2(MapIn) returns (MapOut);
-}
diff --git a/src/google/protobuf/util/internal/testdata/oneofs.proto b/src/google/protobuf/util/internal/testdata/oneofs.proto
index 5bc9fa08..c37da083 100644
--- a/src/google/protobuf/util/internal/testdata/oneofs.proto
+++ b/src/google/protobuf/util/internal/testdata/oneofs.proto
@@ -28,7 +28,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Proto to test oneofs.
+// Proto to test proto3 oneofs.
syntax = "proto3";
import "google/protobuf/any.proto";
@@ -36,7 +36,6 @@ import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
package google.protobuf.testing.oneofs;
-option java_package = "com.google.protobuf.testing.oneofs";
message OneOfsRequest {
string value = 1;
@@ -45,24 +44,34 @@ message OneOfsRequest {
int32 int_data = 3;
// Simple message
Data message_data = 4;
+ MoreData more_data = 5;
// Well known types
- google.protobuf.Struct struct_data = 5;
- google.protobuf.Value value_data = 6;
- google.protobuf.ListValue list_value_data = 7;
- google.protobuf.Timestamp ts_data = 8;
+ google.protobuf.Struct struct_data = 6;
+ google.protobuf.Value value_data = 7;
+ google.protobuf.ListValue list_value_data = 8;
+ google.protobuf.Timestamp ts_data = 9;
}
google.protobuf.Any any_data = 19;
}
+message RequestWithSimpleOneof {
+ string value = 1;
+ oneof data {
+ string str_data = 2;
+ int32 int_data = 3;
+ Data message_data = 4;
+ MoreData more_data = 5;
+ }
+}
+
message Data {
int32 data_value = 1;
}
-message Response {
- string value = 1;
+message MoreData {
+ string str_value = 1;
}
-service TestService {
- // Test call.
- rpc Call(OneOfsRequest) returns (Response);
+message Response {
+ string value = 1;
}
diff --git a/src/google/protobuf/util/internal/testdata/proto3.proto b/src/google/protobuf/util/internal/testdata/proto3.proto
new file mode 100644
index 00000000..c013cee3
--- /dev/null
+++ b/src/google/protobuf/util/internal/testdata/proto3.proto
@@ -0,0 +1,42 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc. All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+syntax = "proto3";
+
+package google.protobuf.testing;
+
+message Proto3Message {
+ enum NestedEnum {
+ FOO = 0;
+ BAR = 1;
+ BAZ = 2;
+ }
+ NestedEnum enum_value = 1;
+}
diff --git a/src/google/protobuf/util/internal/testdata/struct.proto b/src/google/protobuf/util/internal/testdata/struct.proto
index c15aba0d..7b1cc1b9 100644
--- a/src/google/protobuf/util/internal/testdata/struct.proto
+++ b/src/google/protobuf/util/internal/testdata/struct.proto
@@ -28,18 +28,90 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Proto to test proto3 struct.
syntax = "proto3";
-package google.protobuf.testing.structs;
-option java_package = "com.google.protobuf.testing.structs";
+package google.protobuf.testing;
import "google/protobuf/struct.proto";
-message StructType {
- google.protobuf.Struct object = 1;
+message StructTestCases {
+ StructWrapper empty_value = 1;
+ StructWrapper empty_value2 = 2;
+ StructWrapper null_value = 3;
+ StructWrapper simple_struct = 4;
+ StructWrapper longer_struct = 5;
+ StructWrapper struct_with_nested_struct = 6;
+ StructWrapper struct_with_nested_list = 7;
+ StructWrapper struct_with_list_of_nulls = 8;
+ StructWrapper struct_with_list_of_lists = 9;
+ StructWrapper struct_with_list_of_structs = 10;
+ StructWrapper struct_with_empty_list = 11;
+ StructWrapper struct_with_list_with_empty_struct = 12;
+ google.protobuf.Struct top_level_struct = 13;
+ google.protobuf.Struct top_level_struct_with_empty_list = 14;
+ google.protobuf.Struct top_level_struct_with_list_with_empty_struct = 15;
+ ValueWrapper value_wrapper_simple = 16;
+ ValueWrapper value_wrapper_with_struct = 17;
+ ValueWrapper value_wrapper_with_list = 18;
+ ValueWrapper value_wrapper_with_empty_list = 19;
+ ValueWrapper value_wrapper_with_list_with_empty_struct = 20;
+ ListValueWrapper list_value_wrapper = 21;
+ ListValueWrapper list_value_wrapper_with_empty_list = 22;
+ ListValueWrapper list_value_wrapper_with_list_with_empty_struct = 23;
+ google.protobuf.Value top_level_value_simple = 24;
+ google.protobuf.Value top_level_value_with_struct = 25;
+ google.protobuf.Value top_level_value_with_list = 26;
+ google.protobuf.Value top_level_value_with_empty_list = 27;
+ google.protobuf.Value top_level_value_with_list_with_empty_struct = 28;
+ google.protobuf.ListValue top_level_listvalue = 29;
+ google.protobuf.ListValue top_level_empty_listvalue = 30;
+ google.protobuf.ListValue top_level_listvalue_with_empty_struct = 31;
+ RepeatedValueWrapper repeated_value = 32;
+ RepeatedValueWrapper repeated_value_nested_list = 33;
+ RepeatedValueWrapper repeated_value_nested_list2 = 34;
+ RepeatedValueWrapper repeated_value_nested_list3 = 35;
+ RepeatedListValueWrapper repeated_listvalue = 36;
+ MapOfStruct map_of_struct = 37;
+ MapOfStruct map_of_struct_value = 38;
+ MapOfStruct map_of_listvalue = 39;
+}
+
+message StructWrapper {
+ google.protobuf.Struct struct = 1;
+}
+
+message ValueWrapper {
+ google.protobuf.Value value = 1;
+}
+
+message RepeatedValueWrapper {
+ repeated google.protobuf.Value values = 1;
+}
+
+message ListValueWrapper {
+ google.protobuf.ListValue shopping_list = 1;
}
-service TestService {
- rpc Call(StructType) returns (StructType);
+message RepeatedListValueWrapper {
+ repeated google.protobuf.ListValue dimensions = 1;
+}
+
+message MapOfStruct {
+ map<string, google.protobuf.Struct> struct_map = 1;
+ map<string, google.protobuf.Value> value_map = 2;
+ map<string, google.protobuf.ListValue> listvalue_map = 3;
+}
+
+// Hack to test return types with Struct as top-level message. Struct typers
+// cannot be directly used in API requests. Hence using Dummy as request type.
+message Dummy {
+ string text = 1;
+}
+
+service StructTestService {
+ rpc Call(Dummy) returns (StructTestCases);
+}
+
+message StructType {
+ google.protobuf.Struct object = 1;
}
diff --git a/src/google/protobuf/util/internal/testdata/timestamp_duration.proto b/src/google/protobuf/util/internal/testdata/timestamp_duration.proto
index 56351f16..b74484ce 100644
--- a/src/google/protobuf/util/internal/testdata/timestamp_duration.proto
+++ b/src/google/protobuf/util/internal/testdata/timestamp_duration.proto
@@ -28,20 +28,53 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// Proto to test proto3 Timestamp and Duration.
syntax = "proto3";
-package google.protobuf.testing.timestampduration;
-option java_package = "com.google.protobuf.testing.timestampduration";
+package google.protobuf.testing;
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
+message TimestampDurationTestCases {
+ // Timestamp tests
+ TimeStampType epoch = 1;
+ TimeStampType epoch2 = 2;
+ TimeStampType mintime = 3;
+ TimeStampType maxtime = 4;
+ TimeStampType timeval1 = 5;
+ TimeStampType timeval2 = 6;
+ TimeStampType timeval3 = 7;
+ TimeStampType timeval4 = 8;
+ TimeStampType timeval5 = 9;
+ TimeStampType timeval6 = 10;
+ TimeStampType timeval7 = 11;
+ google.protobuf.Timestamp timeval8 = 12;
+
+ // Duration tests
+ DurationType zero_duration = 101;
+ DurationType min_duration = 102;
+ DurationType max_duration = 103;
+ DurationType duration1 = 104;
+ DurationType duration2 = 105;
+ DurationType duration3 = 106;
+ DurationType duration4 = 107;
+ google.protobuf.Duration duration5 = 108;
+}
+
+message TimeStampType {
+ google.protobuf.Timestamp timestamp = 1;
+}
+
+message DurationType {
+ google.protobuf.Duration duration = 1;
+}
+
+service TimestampDurationTestService {
+ rpc Call(TimestampDurationTestCases) returns (TimestampDurationTestCases);
+}
+
message TimestampDuration {
google.protobuf.Timestamp ts = 1;
google.protobuf.Duration dur = 2;
-}
-
-service TestService {
- rpc Call(TimestampDuration) returns (TimestampDuration);
+ repeated google.protobuf.Timestamp rep_ts = 3;
}
diff --git a/src/google/protobuf/util/internal/utility.cc b/src/google/protobuf/util/internal/utility.cc
index 5f613e77..05328255 100644
--- a/src/google/protobuf/util/internal/utility.cc
+++ b/src/google/protobuf/util/internal/utility.cc
@@ -41,6 +41,8 @@
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/mathlimits.h>
+#include <algorithm>
+
namespace google {
namespace protobuf {
namespace util {
@@ -178,6 +180,19 @@ const google::protobuf::Field* FindJsonFieldInTypeOrNull(
return NULL;
}
+const google::protobuf::Field* FindFieldInTypeByNumberOrNull(
+ const google::protobuf::Type* type, int32 number) {
+ if (type != NULL) {
+ for (int i = 0; i < type->fields_size(); ++i) {
+ const google::protobuf::Field& field = type->fields(i);
+ if (field.number() == number) {
+ return &field;
+ }
+ }
+ }
+ return NULL;
+}
+
const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
const google::protobuf::Enum* enum_type, StringPiece enum_name) {
if (enum_type != NULL) {
@@ -204,6 +219,32 @@ const google::protobuf::EnumValue* FindEnumValueByNumberOrNull(
return NULL;
}
+const google::protobuf::EnumValue* FindEnumValueByNameWithoutUnderscoreOrNull(
+ const google::protobuf::Enum* enum_type, StringPiece enum_name) {
+ if (enum_type != NULL) {
+ 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();
+
+ // Remove underscore from the name.
+ enum_name_without_underscore.erase(
+ std::remove(enum_name_without_underscore.begin(),
+ enum_name_without_underscore.end(), '_'),
+ enum_name_without_underscore.end());
+ // Make the name uppercase.
+ for (string::iterator it = enum_name_without_underscore.begin();
+ it != enum_name_without_underscore.end(); ++it) {
+ *it = ascii_toupper(*it);
+ }
+
+ if (enum_name_without_underscore == enum_name) {
+ return &enum_value;
+ }
+ }
+ }
+ return NULL;
+}
+
string ToCamelCase(const StringPiece input) {
bool capitalize_next = false;
bool was_cap = true;
@@ -315,15 +356,23 @@ bool IsValidBoolString(const string& bool_string) {
bool IsMap(const google::protobuf::Field& field,
const google::protobuf::Type& type) {
- return (field.cardinality() ==
- google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
- GetBoolOptionOrDefault(type.options(),
- "google.protobuf.MessageOptions.map_entry", false));
+ return (
+ field.cardinality() ==
+ google::protobuf::Field_Cardinality_CARDINALITY_REPEATED &&
+ (GetBoolOptionOrDefault(
+ type.options(), "google.protobuf.MessageOptions.map_entry", false) ||
+ GetBoolOptionOrDefault(type.options(), "proto2.MessageOptions.map_entry",
+ false)));
}
bool IsMessageSetWireFormat(const google::protobuf::Type& type) {
- return GetBoolOptionOrDefault(
- type.options(), "google.protobuf.MessageOptions.message_set_wire_format", false);
+ return (
+ GetBoolOptionOrDefault(
+ type.options(),
+ "google.protobuf.MessageOptions.message_set_wire_format", false) ||
+ GetBoolOptionOrDefault(type.options(),
+ "proto2.MessageOptions.message_set_wire_format",
+ false));
}
string DoubleAsString(double value) {
@@ -363,3 +412,4 @@ bool SafeStrToFloat(StringPiece str, float* value) {
} // namespace util
} // namespace protobuf
} // namespace google
+
diff --git a/src/google/protobuf/util/internal/utility.h b/src/google/protobuf/util/internal/utility.h
index 26fed444..667e660c 100644
--- a/src/google/protobuf/util/internal/utility.h
+++ b/src/google/protobuf/util/internal/utility.h
@@ -136,6 +136,10 @@ const google::protobuf::Field* FindFieldInTypeOrNull(
const google::protobuf::Field* FindJsonFieldInTypeOrNull(
const google::protobuf::Type* type, StringPiece json_name);
+// Similar to FindFieldInTypeOrNull, but this looks up fields by number.
+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.
const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
@@ -146,6 +150,13 @@ const google::protobuf::EnumValue* FindEnumValueByNameOrNull(
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.
+// 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(
+ const google::protobuf::Enum* enum_type, StringPiece enum_name);
+
// Converts input to camel-case and returns it.
LIBPROTOBUF_EXPORT string ToCamelCase(const StringPiece input);
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc
index dacac5e0..24ff5fd6 100644
--- a/src/google/protobuf/util/json_util_test.cc
+++ b/src/google/protobuf/util/json_util_test.cc
@@ -128,6 +128,34 @@ TEST_F(JsonUtilTest, TestDefaultValues) {
"\"repeatedMessageValue\":[]"
"}",
ToJson(m, options));
+
+ options.always_print_primitive_fields = true;
+ m.set_string_value("i am a test string value");
+ m.set_bytes_value("i am a test bytes value");
+ EXPECT_EQ(
+ "{\"boolValue\":false,"
+ "\"int32Value\":0,"
+ "\"int64Value\":\"0\","
+ "\"uint32Value\":0,"
+ "\"uint64Value\":\"0\","
+ "\"floatValue\":0,"
+ "\"doubleValue\":0,"
+ "\"stringValue\":\"i am a test string value\","
+ "\"bytesValue\":\"aSBhbSBhIHRlc3QgYnl0ZXMgdmFsdWU=\","
+ "\"enumValue\":\"FOO\","
+ "\"repeatedBoolValue\":[],"
+ "\"repeatedInt32Value\":[],"
+ "\"repeatedInt64Value\":[],"
+ "\"repeatedUint32Value\":[],"
+ "\"repeatedUint64Value\":[],"
+ "\"repeatedFloatValue\":[],"
+ "\"repeatedDoubleValue\":[],"
+ "\"repeatedStringValue\":[],"
+ "\"repeatedBytesValue\":[],"
+ "\"repeatedEnumValue\":[],"
+ "\"repeatedMessageValue\":[]"
+ "}",
+ ToJson(m, options));
}
TEST_F(JsonUtilTest, ParseMessage) {
diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc
index a6d0cb07..328b40d8 100644
--- a/src/google/protobuf/util/message_differencer.cc
+++ b/src/google/protobuf/util/message_differencer.cc
@@ -626,6 +626,7 @@ bool MessageDifferencer::CompareWithFieldsInternal(
}
if (reporter_ != NULL) {
+ assert(field1 != NULL);
int count = field1->is_repeated() ?
reflection1->FieldSize(message1, field1) : 1;
@@ -706,6 +707,7 @@ bool MessageDifferencer::CompareWithFieldsInternal(
}
bool fieldDifferent = false;
+ assert(field1 != NULL);
if (field1->is_repeated()) {
fieldDifferent = !CompareRepeatedField(message1, message2, field1,
parent_fields);
@@ -875,6 +877,7 @@ bool MessageDifferencer::CompareRepeatedField(
for (int i = 0; i < count1; ++i) {
if (match_list1[i] != -1) continue;
+ assert(reporter_ != NULL);
specific_field.index = i;
parent_fields->push_back(specific_field);
reporter_->ReportDeleted(message1, message2, *parent_fields);
@@ -1389,8 +1392,7 @@ bool MessageDifferencer::MatchRepeatedFieldIndices(
// doesn't necessarily imply Compare(b, c). Therefore a naive greedy
// algorithm will fail to find a maximum matching.
// Here we use the argumenting path algorithm.
- MaximumMatcher::NodeMatchCallback* callback =
- ::google::protobuf::internal::NewPermanentCallback(
+ MaximumMatcher::NodeMatchCallback* callback = NewPermanentCallback(
this, &MessageDifferencer::IsMatch,
repeated_field, key_comparator,
&message1, &message2, parent_fields);
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h
index 654d1a67..fde37cf9 100644
--- a/src/google/protobuf/util/message_differencer.h
+++ b/src/google/protobuf/util/message_differencer.h
@@ -221,19 +221,19 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// Reports that a field has been added into Message2.
virtual void ReportAdded(
const Message& message1, const Message& message2,
- const vector<SpecificField>& field_path) = 0;
+ const std::vector<SpecificField>& field_path) = 0;
// Reports that a field has been deleted from Message1.
virtual void ReportDeleted(
const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path) = 0;
+ const std::vector<SpecificField>& field_path) = 0;
// Reports that the value of a field has been modified.
virtual void ReportModified(
const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path) = 0;
+ const std::vector<SpecificField>& field_path) = 0;
// Reports that a repeated field has been moved to another location. This
// only applies when using TreatAsSet or TreatAsMap() -- see below. Also
@@ -243,7 +243,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
virtual void ReportMoved(
const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path) { }
+ const std::vector<SpecificField>& field_path) { }
// Reports that two fields match. Useful for doing side-by-side diffs.
// This function is mutually exclusive with ReportModified and ReportMoved.
@@ -252,7 +252,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
virtual void ReportMatched(
const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path) { }
+ const std::vector<SpecificField>& field_path) { }
// Reports that two fields would have been compared, but the
// comparison has been skipped because the field was marked as
@@ -276,14 +276,14 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
virtual void ReportIgnored(
const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path) { }
+ const std::vector<SpecificField>& field_path) { }
// Report that an unknown field is ignored. (see comment above).
// Note this is a different function since the last SpecificField in field
// path has a null field. This could break existing Reporter.
virtual void ReportUnknownFieldIgnored(
const Message& message1, const Message& message2,
- const vector<SpecificField>& field_path) {}
+ const std::vector<SpecificField>& field_path) {}
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reporter);
@@ -296,9 +296,10 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
MapKeyComparator();
virtual ~MapKeyComparator();
- virtual bool IsMatch(const Message& message1,
- const Message& message2,
- const vector<SpecificField>& parent_fields) const {
+ virtual bool IsMatch(
+ const Message& message1,
+ const Message& message2,
+ const std::vector<SpecificField>& parent_fields) const {
GOOGLE_CHECK(false) << "IsMatch() is not implemented.";
return false;
}
@@ -323,7 +324,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
const Message& message1,
const Message& message2,
const FieldDescriptor* field,
- const vector<SpecificField>& parent_fields) = 0;
+ const std::vector<SpecificField>& parent_fields) = 0;
// Returns true if the unknown field should be ignored.
// Note: This will be called for unknown fields as well in which case
@@ -331,7 +332,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
virtual bool IsUnknownFieldIgnored(
const Message& message1, const Message& message2,
const SpecificField& field,
- const vector<SpecificField>& parent_fields) {
+ const std::vector<SpecificField>& parent_fields) {
return false;
}
};
@@ -440,7 +441,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// size of each element.
void TreatAsMapWithMultipleFieldsAsKey(
const FieldDescriptor* field,
- const vector<const FieldDescriptor*>& key_fields);
+ const std::vector<const FieldDescriptor*>& key_fields);
// Same as TreatAsMapWithMultipleFieldsAsKey, except that each of the field
// do not necessarily need to be a direct subfield. Each element in
// key_field_paths indicate a path from the message being compared, listing
@@ -456,7 +457,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// !key_field_path[i]->is_repeated()
void TreatAsMapWithMultipleFieldPathsAsKey(
const FieldDescriptor* field,
- const vector<vector<const FieldDescriptor*> >& key_field_paths);
+ const std::vector<std::vector<const FieldDescriptor*> >& key_field_paths);
// Uses a custom MapKeyComparator to determine if two elements have the same
// key when comparing a repeated field as a map.
@@ -549,9 +550,10 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// Same as above, except comparing only the list of fields specified by the
// two vectors of FieldDescriptors.
- bool CompareWithFields(const Message& message1, const Message& message2,
- const vector<const FieldDescriptor*>& message1_fields,
- const vector<const FieldDescriptor*>& message2_fields);
+ bool CompareWithFields(
+ const Message& message1, const Message& message2,
+ const std::vector<const FieldDescriptor*>& message1_fields,
+ const std::vector<const FieldDescriptor*>& message2_fields);
// Automatically creates a reporter that will output the differences
// found (if any) to the specified output string pointer. Note that this
@@ -591,35 +593,35 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// The following are implementations of the methods described above.
virtual void ReportAdded(const Message& message1, const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
virtual void ReportDeleted(const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
virtual void ReportModified(const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
virtual void ReportMoved(const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
virtual void ReportMatched(const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
virtual void ReportIgnored(const Message& message1,
const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
virtual void ReportUnknownFieldIgnored(
const Message& message1, const Message& message2,
- const vector<SpecificField>& field_path);
+ const std::vector<SpecificField>& field_path);
protected:
// Prints the specified path of fields to the buffer.
- virtual void PrintPath(const vector<SpecificField>& field_path,
+ virtual void PrintPath(const std::vector<SpecificField>& field_path,
bool left_side);
// Prints the value of fields to the buffer. left_side is true if the
@@ -628,7 +630,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// unknown_field_index1 or unknown_field_index2 when an unknown field
// is encountered in field_path.
virtual void PrintValue(const Message& message,
- const vector<SpecificField>& field_path,
+ const std::vector<SpecificField>& field_path,
bool left_side);
// Prints the specified path of unknown fields to the buffer.
@@ -659,11 +661,11 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// All fields present in both lists will always be included in the combined
// list. Fields only present in one of the lists will only appear in the
// combined list if the corresponding fields_scope option is set to FULL.
- void CombineFields(const vector<const FieldDescriptor*>& fields1,
+ void CombineFields(const std::vector<const FieldDescriptor*>& fields1,
Scope fields1_scope,
- const vector<const FieldDescriptor*>& fields2,
+ const std::vector<const FieldDescriptor*>& fields2,
Scope fields2_scope,
- vector<const FieldDescriptor*>* combined_fields);
+ std::vector<const FieldDescriptor*>* combined_fields);
// Internal version of the Compare method which performs the actual
// comparison. The parent_fields vector is a vector containing field
@@ -671,34 +673,34 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// (i.e. if the current message is an embedded message, the parent_fields
// vector will contain the field that has this embedded message).
bool Compare(const Message& message1, const Message& message2,
- vector<SpecificField>* parent_fields);
+ std::vector<SpecificField>* parent_fields);
// Compares all the unknown fields in two messages.
bool CompareUnknownFields(const Message& message1, const Message& message2,
const google::protobuf::UnknownFieldSet&,
const google::protobuf::UnknownFieldSet&,
- vector<SpecificField>* parent_fields);
+ std::vector<SpecificField>* parent_fields);
// Compares the specified messages for the requested field lists. The field
// lists are modified depending on comparison settings, and then passed to
// CompareWithFieldsInternal.
bool CompareRequestedFieldsUsingSettings(
const Message& message1, const Message& message2,
- const vector<const FieldDescriptor*>& message1_fields,
- const vector<const FieldDescriptor*>& message2_fields,
- vector<SpecificField>* parent_fields);
+ const std::vector<const FieldDescriptor*>& message1_fields,
+ const std::vector<const FieldDescriptor*>& message2_fields,
+ std::vector<SpecificField>* parent_fields);
// Compares the specified messages with the specified field lists.
bool CompareWithFieldsInternal(
const Message& message1, const Message& message2,
- const vector<const FieldDescriptor*>& message1_fields,
- const vector<const FieldDescriptor*>& message2_fields,
- vector<SpecificField>* parent_fields);
+ const std::vector<const FieldDescriptor*>& message1_fields,
+ const std::vector<const FieldDescriptor*>& message2_fields,
+ std::vector<SpecificField>* parent_fields);
// Compares the repeated fields, and report the error.
bool CompareRepeatedField(const Message& message1, const Message& message2,
const FieldDescriptor* field,
- vector<SpecificField>* parent_fields);
+ std::vector<SpecificField>* parent_fields);
// Shorthand for CompareFieldValueUsingParentFields with NULL parent_fields.
bool CompareFieldValue(const Message& message1,
@@ -716,12 +718,13 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// list of parent messages if it needs to recursively compare the given field.
// To avoid confusing users you should not set it to NULL unless you modified
// Reporter to handle the change of parent_fields correctly.
- bool CompareFieldValueUsingParentFields(const Message& message1,
- const Message& message2,
- const FieldDescriptor* field,
- int index1,
- int index2,
- vector<SpecificField>* parent_fields);
+ bool CompareFieldValueUsingParentFields(
+ const Message& message1,
+ const Message& message2,
+ const FieldDescriptor* field,
+ int index1,
+ int index2,
+ std::vector<SpecificField>* parent_fields);
// Compares the specified field on the two messages, returning comparison
// result, as returned by appropriate FieldComparator.
@@ -736,7 +739,7 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
bool IsMatch(const FieldDescriptor* repeated_field,
const MapKeyComparator* key_comparator,
const Message* message1, const Message* message2,
- const vector<SpecificField>& parent_fields,
+ const std::vector<SpecificField>& parent_fields,
int index1, int index2);
// Returns true when this repeated field has been configured to be treated
@@ -754,13 +757,13 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
const Message& message1,
const Message& message2,
const FieldDescriptor* field,
- const vector<SpecificField>& parent_fields);
+ const std::vector<SpecificField>& parent_fields);
// Returns true if this unknown field is to be ignored when this
// MessageDifferencer compares messages.
bool IsUnknownFieldIgnored(const Message& message1, const Message& message2,
const SpecificField& field,
- const vector<SpecificField>& parent_fields);
+ const std::vector<SpecificField>& parent_fields);
// Returns MapKeyComparator* when this field has been configured to
// be treated as a map. If not, returns NULL.
@@ -773,28 +776,29 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// This method returns false if the match failed. However, it doesn't mean
// that the comparison succeeds when this method returns true (you need to
// double-check in this case).
- bool MatchRepeatedFieldIndices(const Message& message1,
- const Message& message2,
- const FieldDescriptor* repeated_field,
- const vector<SpecificField>& parent_fields,
- vector<int>* match_list1,
- vector<int>* match_list2);
+ bool MatchRepeatedFieldIndices(
+ const Message& message1,
+ const Message& message2,
+ const FieldDescriptor* repeated_field,
+ const std::vector<SpecificField>& parent_fields,
+ std::vector<int>* match_list1,
+ std::vector<int>* match_list2);
// 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);
// Checks if index is equal to new_index in all the specific fields.
- static bool CheckPathChanged(const vector<SpecificField>& parent_fields);
+ static bool CheckPathChanged(const std::vector<SpecificField>& parent_fields);
// Defines a map between field descriptors and their MapKeyComparators.
// Used for repeated fields when they are configured as TreatAsMap.
- typedef map<const FieldDescriptor*,
+ typedef std::map<const FieldDescriptor*,
const MapKeyComparator*> FieldKeyComparatorMap;
// Defines a set to store field descriptors. Used for repeated fields when
// they are configured as TreatAsSet.
- typedef set<const FieldDescriptor*> FieldSet;
+ typedef std::set<const FieldDescriptor*> FieldSet;
Reporter* reporter_;
DefaultFieldComparator default_field_comparator_;
@@ -811,9 +815,9 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
// When TreatAsMap or TreatAsMapWithMultipleFieldsAsKey is called, we don't
// store the supplied FieldDescriptors directly. Instead, a new
// MapKeyComparator is created for comparison purpose.
- vector<MapKeyComparator*> owned_key_comparators_;
+ std::vector<MapKeyComparator*> owned_key_comparators_;
FieldKeyComparatorMap map_field_key_comparator_;
- vector<IgnoreCriteria*> ignore_criteria_;
+ std::vector<IgnoreCriteria*> ignore_criteria_;
FieldSet ignored_fields_;
@@ -831,15 +835,15 @@ class LIBPROTOBUF_EXPORT MessageDifferencer {
class LIBPROTOBUF_EXPORT FieldContext {
public:
explicit FieldContext(
- vector<MessageDifferencer::SpecificField>* parent_fields)
+ std::vector<MessageDifferencer::SpecificField>* parent_fields)
: parent_fields_(parent_fields) {}
- vector<MessageDifferencer::SpecificField>* parent_fields() const {
+ std::vector<MessageDifferencer::SpecificField>* parent_fields() const {
return parent_fields_;
}
private:
- vector<MessageDifferencer::SpecificField>* parent_fields_;
+ std::vector<MessageDifferencer::SpecificField>* parent_fields_;
};
}
diff --git a/src/google/protobuf/util/package_info.h b/src/google/protobuf/util/package_info.h
new file mode 100644
index 00000000..e37e6dc0
--- /dev/null
+++ b/src/google/protobuf/util/package_info.h
@@ -0,0 +1,46 @@
+// 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 exists solely to document the google::protobuf::util namespace.
+// It is not compiled into anything, but it may be read by an automated
+// documentation generator.
+
+namespace google {
+
+namespace protobuf {
+
+// Utility classes.
+//
+// This package contains various utilities for message comprasion, JSON
+// conversion, well known types, etc.
+namespace util {}
+
+} // namespace protobuf
+} // namespace google
diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc
index 031d019a..b11f822a 100644
--- a/src/google/protobuf/util/time_util.cc
+++ b/src/google/protobuf/util/time_util.cc
@@ -143,11 +143,13 @@ int64 RoundTowardZero(int64 value, int64 divider) {
} // namespace
// Actually define these static const integers. Required by C++ standard (but
-// omitting them may still work with some compilers).
+// some compilers don't like it).
+#ifndef _MSC_VER
const int64 TimeUtil::kTimestampMinSeconds;
const int64 TimeUtil::kTimestampMaxSeconds;
const int64 TimeUtil::kDurationMaxSeconds;
const int64 TimeUtil::kDurationMinSeconds;
+#endif // !_MSC_VER
string TimeUtil::ToString(const Timestamp& timestamp) {
return FormatTime(timestamp.seconds(), timestamp.nanos());
diff --git a/src/google/protobuf/util/time_util.h b/src/google/protobuf/util/time_util.h
index 1bac0897..432c9f0a 100644
--- a/src/google/protobuf/util/time_util.h
+++ b/src/google/protobuf/util/time_util.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Defines utilities for the Timestamp and Duration well known types.
+
#ifndef GOOGLE_PROTOBUF_UTIL_TIME_UTIL_H__
#define GOOGLE_PROTOBUF_UTIL_TIME_UTIL_H__
@@ -47,6 +49,7 @@ namespace google {
namespace protobuf {
namespace util {
+// Utility functions for Timestamp and Duration.
class LIBPROTOBUF_EXPORT TimeUtil {
typedef google::protobuf::Timestamp Timestamp;
typedef google::protobuf::Duration Duration;
diff --git a/src/google/protobuf/util/type_resolver.h b/src/google/protobuf/util/type_resolver.h
index 77d4416a..959f3c79 100644
--- a/src/google/protobuf/util/type_resolver.h
+++ b/src/google/protobuf/util/type_resolver.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Defines a TypeResolver for the Any message.
+
#ifndef GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_H__
#define GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_H__
diff --git a/src/google/protobuf/util/type_resolver_util.h b/src/google/protobuf/util/type_resolver_util.h
index c0ef3c1a..c17366fc 100644
--- a/src/google/protobuf/util/type_resolver_util.h
+++ b/src/google/protobuf/util/type_resolver_util.h
@@ -28,6 +28,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+// Defines utilities for the TypeResolver.
+
#ifndef GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_UTIL_H__
#define GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_UTIL_H__
diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc
index 5ee4e25d..147478be 100644
--- a/src/google/protobuf/wire_format.cc
+++ b/src/google/protobuf/wire_format.cc
@@ -307,9 +307,9 @@ uint8* WireFormat::SerializeUnknownMessageSetItemsToArray(
return target;
}
-int WireFormat::ComputeUnknownFieldsSize(
+size_t WireFormat::ComputeUnknownFieldsSize(
const UnknownFieldSet& unknown_fields) {
- int size = 0;
+ size_t size = 0;
for (int i = 0; i < unknown_fields.field_count(); i++) {
const UnknownField& field = unknown_fields.field(i);
@@ -355,9 +355,9 @@ int WireFormat::ComputeUnknownFieldsSize(
return size;
}
-int WireFormat::ComputeUnknownMessageSetItemsSize(
+size_t WireFormat::ComputeUnknownMessageSetItemsSize(
const UnknownFieldSet& unknown_fields) {
- int size = 0;
+ size_t size = 0;
for (int i = 0; i < unknown_fields.field_count(); i++) {
const UnknownField& field = unknown_fields.field(i);
@@ -838,7 +838,7 @@ void WireFormat::SerializeFieldWithCachedSizes(
if (is_packed && count > 0) {
WireFormatLite::WriteTag(field->number(),
WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
- const int data_size = FieldDataOnlyByteSize(field, message);
+ const size_t data_size = FieldDataOnlyByteSize(field, message);
output->WriteVarint32(data_size);
}
@@ -964,11 +964,11 @@ void WireFormat::SerializeMessageSetItemWithCachedSizes(
// ===================================================================
-int WireFormat::ByteSize(const Message& message) {
+size_t WireFormat::ByteSize(const Message& message) {
const Descriptor* descriptor = message.GetDescriptor();
const Reflection* message_reflection = message.GetReflection();
- int our_size = 0;
+ size_t our_size = 0;
vector<const FieldDescriptor*> fields;
message_reflection->ListFields(message, &fields);
@@ -987,7 +987,7 @@ int WireFormat::ByteSize(const Message& message) {
return our_size;
}
-int WireFormat::FieldByteSize(
+size_t WireFormat::FieldByteSize(
const FieldDescriptor* field,
const Message& message) {
const Reflection* message_reflection = message.GetReflection();
@@ -999,15 +999,15 @@ int WireFormat::FieldByteSize(
return MessageSetItemByteSize(field, message);
}
- int count = 0;
+ size_t count = 0;
if (field->is_repeated()) {
- count = message_reflection->FieldSize(message, field);
+ count = FromIntSize(message_reflection->FieldSize(message, field));
} else if (message_reflection->HasField(message, field)) {
count = 1;
}
- const int data_size = FieldDataOnlyByteSize(field, message);
- int our_size = data_size;
+ const size_t data_size = FieldDataOnlyByteSize(field, message);
+ size_t our_size = data_size;
if (field->is_packed()) {
if (data_size > 0) {
// Packed fields get serialized like a string, not their native type.
@@ -1022,19 +1022,20 @@ int WireFormat::FieldByteSize(
return our_size;
}
-int WireFormat::FieldDataOnlyByteSize(
+size_t WireFormat::FieldDataOnlyByteSize(
const FieldDescriptor* field,
const Message& message) {
const Reflection* message_reflection = message.GetReflection();
- int count = 0;
+ size_t count = 0;
if (field->is_repeated()) {
- count = message_reflection->FieldSize(message, field);
+ count =
+ internal::FromIntSize(message_reflection->FieldSize(message, field));
} else if (message_reflection->HasField(message, field)) {
count = 1;
}
- int data_size = 0;
+ size_t data_size = 0;
switch (field->type()) {
#define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \
case FieldDescriptor::TYPE_##TYPE: \
@@ -1108,19 +1109,19 @@ int WireFormat::FieldDataOnlyByteSize(
return data_size;
}
-int WireFormat::MessageSetItemByteSize(
+size_t WireFormat::MessageSetItemByteSize(
const FieldDescriptor* field,
const Message& message) {
const Reflection* message_reflection = message.GetReflection();
- int our_size = WireFormatLite::kMessageSetItemTagsSize;
+ size_t our_size = WireFormatLite::kMessageSetItemTagsSize;
// type_id
our_size += io::CodedOutputStream::VarintSize32(field->number());
// message
const Message& sub_message = message_reflection->GetMessage(message, field);
- int message_size = sub_message.ByteSize();
+ size_t message_size = sub_message.ByteSizeLong();
our_size += io::CodedOutputStream::VarintSize32(message_size);
our_size += message_size;
diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h
index aaee21f0..de8ea574 100644
--- a/src/google/protobuf/wire_format.h
+++ b/src/google/protobuf/wire_format.h
@@ -85,7 +85,7 @@ class LIBPROTOBUF_EXPORT WireFormat {
// Compute the byte size of a tag. For groups, this includes both the start
// and end tags.
- static inline int TagSize(int field_number, FieldDescriptor::Type type);
+ static inline size_t TagSize(int field_number, FieldDescriptor::Type type);
// These procedures can be used to implement the methods of Message which
// handle parsing and serialization of the protocol buffer wire format
@@ -122,7 +122,7 @@ class LIBPROTOBUF_EXPORT WireFormat {
// will have their ByteSize() methods called, so their sizes will be cached.
// Therefore, calling this method is sufficient to allow you to call
// WireFormat::SerializeWithCachedSizes() on the same object.
- static int ByteSize(const Message& message);
+ static size_t ByteSize(const Message& message);
// -----------------------------------------------------------------
// Helpers for dealing with unknown fields
@@ -173,11 +173,11 @@ class LIBPROTOBUF_EXPORT WireFormat {
uint8* target);
// Compute the size of the UnknownFieldSet on the wire.
- static int ComputeUnknownFieldsSize(const UnknownFieldSet& unknown_fields);
+ static size_t ComputeUnknownFieldsSize(const UnknownFieldSet& unknown_fields);
// Same thing except for messages that have the message_set_wire_format
// option.
- static int ComputeUnknownMessageSetItemsSize(
+ static size_t ComputeUnknownMessageSetItemsSize(
const UnknownFieldSet& unknown_fields);
@@ -205,7 +205,7 @@ class LIBPROTOBUF_EXPORT WireFormat {
// Compute size of a single field. If the field is a message type, this
// will call ByteSize() for the embedded message, insuring that it caches
// its size.
- static int FieldByteSize(
+ static size_t FieldByteSize(
const FieldDescriptor* field, // Cannot be NULL
const Message& message);
@@ -218,7 +218,7 @@ class LIBPROTOBUF_EXPORT WireFormat {
const FieldDescriptor* field,
const Message& message,
io::CodedOutputStream* output);
- static int MessageSetItemByteSize(
+ static size_t MessageSetItemByteSize(
const FieldDescriptor* field,
const Message& message);
@@ -226,7 +226,7 @@ class LIBPROTOBUF_EXPORT WireFormat {
// only includes the size of the raw data, and not the size of the total
// length, but for other length-delimited types, the size of the length is
// included.
- static int FieldDataOnlyByteSize(
+ static size_t FieldDataOnlyByteSize(
const FieldDescriptor* field, // Cannot be NULL
const Message& message);
@@ -301,7 +301,8 @@ inline uint32 WireFormat::MakeTag(const FieldDescriptor* field) {
return WireFormatLite::MakeTag(field->number(), WireTypeForField(field));
}
-inline int WireFormat::TagSize(int field_number, FieldDescriptor::Type type) {
+inline size_t WireFormat::TagSize(int field_number,
+ FieldDescriptor::Type type) {
// Some compilers don't like enum -> enum casts, so we implicit_cast to
// int first.
return WireFormatLite::TagSize(field_number,
diff --git a/src/google/protobuf/wire_format_lite.cc b/src/google/protobuf/wire_format_lite.cc
index 05cc0854..5bed7af4 100644
--- a/src/google/protobuf/wire_format_lite.cc
+++ b/src/google/protobuf/wire_format_lite.cc
@@ -61,7 +61,7 @@ const int WireFormatLite::kMessageSetMessageTag;
#endif
// IBM xlC requires prefixing constants with WireFormatLite::
-const int WireFormatLite::kMessageSetItemTagsSize =
+const size_t WireFormatLite::kMessageSetItemTagsSize =
io::CodedOutputStream::StaticVarintSize32<
WireFormatLite::kMessageSetItemStartTag>::value +
io::CodedOutputStream::StaticVarintSize32<
diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h
index 580d4db0..eeb3650f 100644
--- a/src/google/protobuf/wire_format_lite.h
+++ b/src/google/protobuf/wire_format_lite.h
@@ -155,7 +155,8 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// Compute the byte size of a tag. For groups, this includes both the start
// and end tags.
- static inline int TagSize(int field_number, WireFormatLite::FieldType type);
+ static inline size_t TagSize(int field_number,
+ WireFormatLite::FieldType type);
// Skips a field value with the given tag. The input should start
// positioned immediately after the tag. Skipped values are simply discarded,
@@ -212,7 +213,7 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
// Byte size of all tags of a MessageSet::Item combined.
- static const int kMessageSetItemTagsSize;
+ static const size_t kMessageSetItemTagsSize;
// Helper functions for converting between floats/doubles and IEEE-754
// uint32s/uint64s so that they can be written. (Assumes your platform
@@ -510,40 +511,40 @@ class LIBPROTOBUF_EXPORT WireFormatLite {
// the tag, so you must also call TagSize(). (This is because, for repeated
// fields, you should only call TagSize() once and multiply it by the element
// count, but you may have to call XxSize() for each individual element.)
- static inline int Int32Size ( int32 value);
- static inline int Int64Size ( int64 value);
- static inline int UInt32Size (uint32 value);
- static inline int UInt64Size (uint64 value);
- static inline int SInt32Size ( int32 value);
- static inline int SInt64Size ( int64 value);
- static inline int EnumSize ( int value);
+ static inline size_t Int32Size ( int32 value);
+ static inline size_t Int64Size ( int64 value);
+ static inline size_t UInt32Size (uint32 value);
+ static inline size_t UInt64Size (uint64 value);
+ static inline size_t SInt32Size ( int32 value);
+ static inline size_t SInt64Size ( int64 value);
+ static inline size_t EnumSize ( int value);
// These types always have the same size.
- static const int kFixed32Size = 4;
- static const int kFixed64Size = 8;
- static const int kSFixed32Size = 4;
- static const int kSFixed64Size = 8;
- static const int kFloatSize = 4;
- static const int kDoubleSize = 8;
- static const int kBoolSize = 1;
+ static const size_t kFixed32Size = 4;
+ static const size_t kFixed64Size = 8;
+ static const size_t kSFixed32Size = 4;
+ static const size_t kSFixed64Size = 8;
+ static const size_t kFloatSize = 4;
+ static const size_t kDoubleSize = 8;
+ static const size_t kBoolSize = 1;
- static inline int StringSize(const string& value);
- static inline int BytesSize (const string& value);
+ static inline size_t StringSize(const string& value);
+ static inline size_t BytesSize (const string& value);
- static inline int GroupSize (const MessageLite& value);
- static inline int MessageSize(const MessageLite& value);
+ static inline size_t GroupSize (const MessageLite& value);
+ static inline size_t MessageSize(const MessageLite& value);
// Like above, but de-virtualize the call to ByteSize(). The
// pointer must point at an instance of MessageType, *not* a subclass (or
// the subclass must not override ByteSize()).
template<typename MessageType>
- static inline int GroupSizeNoVirtual (const MessageType& value);
+ static inline size_t GroupSizeNoVirtual (const MessageType& value);
template<typename MessageType>
- static inline int MessageSizeNoVirtual(const MessageType& value);
+ static inline size_t MessageSizeNoVirtual(const MessageType& value);
// Given the length of data, calculate the byte size of the data on the
// wire if we encode the data as a length delimited field.
- static inline int LengthDelimitedSize(int length);
+ static inline size_t LengthDelimitedSize(size_t length);
private:
// A helper method for the repeated primitive reader. This method has
@@ -626,9 +627,9 @@ inline int WireFormatLite::GetTagFieldNumber(uint32 tag) {
return static_cast<int>(tag >> kTagTypeBits);
}
-inline int WireFormatLite::TagSize(int field_number,
- WireFormatLite::FieldType type) {
- int result = io::CodedOutputStream::VarintSize32(
+inline size_t WireFormatLite::TagSize(int field_number,
+ WireFormatLite::FieldType type) {
+ size_t result = io::CodedOutputStream::VarintSize32(
field_number << kTagTypeBits);
if (type == TYPE_GROUP) {
// Groups have both a start and an end tag.
diff --git a/src/google/protobuf/wire_format_lite_inl.h b/src/google/protobuf/wire_format_lite_inl.h
index 93d7c824..1963fac8 100644
--- a/src/google/protobuf/wire_format_lite_inl.h
+++ b/src/google/protobuf/wire_format_lite_inl.h
@@ -251,7 +251,7 @@ inline bool WireFormatLite::ReadRepeatedFixedSizePrimitive(
uint32 tag,
io::CodedInputStream* input,
RepeatedField<CType>* values) {
- GOOGLE_DCHECK_EQ(UInt32Size(tag), tag_size);
+ GOOGLE_DCHECK_EQ(UInt32Size(tag), static_cast<size_t>(tag_size));
CType value;
if (!ReadPrimitive<CType, DeclaredType>(input, &value))
return false;
@@ -810,62 +810,58 @@ inline uint8* WireFormatLite::InternalWriteMessageNoVirtualToArray(
// ===================================================================
-inline int WireFormatLite::Int32Size(int32 value) {
+inline size_t WireFormatLite::Int32Size(int32 value) {
return io::CodedOutputStream::VarintSize32SignExtended(value);
}
-inline int WireFormatLite::Int64Size(int64 value) {
+inline size_t WireFormatLite::Int64Size(int64 value) {
return io::CodedOutputStream::VarintSize64(static_cast<uint64>(value));
}
-inline int WireFormatLite::UInt32Size(uint32 value) {
+inline size_t WireFormatLite::UInt32Size(uint32 value) {
return io::CodedOutputStream::VarintSize32(value);
}
-inline int WireFormatLite::UInt64Size(uint64 value) {
+inline size_t WireFormatLite::UInt64Size(uint64 value) {
return io::CodedOutputStream::VarintSize64(value);
}
-inline int WireFormatLite::SInt32Size(int32 value) {
+inline size_t WireFormatLite::SInt32Size(int32 value) {
return io::CodedOutputStream::VarintSize32(ZigZagEncode32(value));
}
-inline int WireFormatLite::SInt64Size(int64 value) {
+inline size_t WireFormatLite::SInt64Size(int64 value) {
return io::CodedOutputStream::VarintSize64(ZigZagEncode64(value));
}
-inline int WireFormatLite::EnumSize(int value) {
+inline size_t WireFormatLite::EnumSize(int value) {
return io::CodedOutputStream::VarintSize32SignExtended(value);
}
-inline int WireFormatLite::StringSize(const string& value) {
- return static_cast<int>(
- io::CodedOutputStream::VarintSize32(static_cast<uint32>(value.size())) +
- value.size());
+inline size_t WireFormatLite::StringSize(const string& value) {
+ return LengthDelimitedSize(value.size());
}
-inline int WireFormatLite::BytesSize(const string& value) {
- return static_cast<int>(
- io::CodedOutputStream::VarintSize32(static_cast<uint32>(value.size())) +
- value.size());
+inline size_t WireFormatLite::BytesSize(const string& value) {
+ return LengthDelimitedSize(value.size());
}
-inline int WireFormatLite::GroupSize(const MessageLite& value) {
- return value.ByteSize();
+inline size_t WireFormatLite::GroupSize(const MessageLite& value) {
+ return value.ByteSizeLong();
}
-inline int WireFormatLite::MessageSize(const MessageLite& value) {
- return LengthDelimitedSize(value.ByteSize());
+inline size_t WireFormatLite::MessageSize(const MessageLite& value) {
+ return LengthDelimitedSize(value.ByteSizeLong());
}
// See comment on ReadGroupNoVirtual to understand the need for this template
// parameter name.
template<typename MessageType_WorkAroundCppLookupDefect>
-inline int WireFormatLite::GroupSizeNoVirtual(
+inline size_t WireFormatLite::GroupSizeNoVirtual(
const MessageType_WorkAroundCppLookupDefect& value) {
- return value.MessageType_WorkAroundCppLookupDefect::ByteSize();
+ return value.MessageType_WorkAroundCppLookupDefect::ByteSizeLong();
}
template<typename MessageType_WorkAroundCppLookupDefect>
-inline int WireFormatLite::MessageSizeNoVirtual(
+inline size_t WireFormatLite::MessageSizeNoVirtual(
const MessageType_WorkAroundCppLookupDefect& value) {
return LengthDelimitedSize(
- value.MessageType_WorkAroundCppLookupDefect::ByteSize());
+ value.MessageType_WorkAroundCppLookupDefect::ByteSizeLong());
}
-inline int WireFormatLite::LengthDelimitedSize(int length) {
+inline size_t WireFormatLite::LengthDelimitedSize(size_t length) {
return io::CodedOutputStream::VarintSize32(length) + length;
}
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc
index 33a69d3b..35364066 100644
--- a/src/google/protobuf/wrappers.pb.cc
+++ b/src/google/protobuf/wrappers.pb.cc
@@ -67,14 +67,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
DoubleValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
DoubleValue_descriptor_,
- DoubleValue::default_instance_,
+ DoubleValue::internal_default_instance(),
DoubleValue_offsets_,
-1,
-1,
-1,
sizeof(DoubleValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DoubleValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DoubleValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DoubleValue, _internal_metadata_));
FloatValue_descriptor_ = file->message_type(1);
static const int FloatValue_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FloatValue, value_),
@@ -82,14 +81,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
FloatValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
FloatValue_descriptor_,
- FloatValue::default_instance_,
+ FloatValue::internal_default_instance(),
FloatValue_offsets_,
-1,
-1,
-1,
sizeof(FloatValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FloatValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FloatValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FloatValue, _internal_metadata_));
Int64Value_descriptor_ = file->message_type(2);
static const int Int64Value_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int64Value, value_),
@@ -97,14 +95,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
Int64Value_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Int64Value_descriptor_,
- Int64Value::default_instance_,
+ Int64Value::internal_default_instance(),
Int64Value_offsets_,
-1,
-1,
-1,
sizeof(Int64Value),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int64Value, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int64Value, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int64Value, _internal_metadata_));
UInt64Value_descriptor_ = file->message_type(3);
static const int UInt64Value_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt64Value, value_),
@@ -112,14 +109,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
UInt64Value_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
UInt64Value_descriptor_,
- UInt64Value::default_instance_,
+ UInt64Value::internal_default_instance(),
UInt64Value_offsets_,
-1,
-1,
-1,
sizeof(UInt64Value),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt64Value, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt64Value, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt64Value, _internal_metadata_));
Int32Value_descriptor_ = file->message_type(4);
static const int Int32Value_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int32Value, value_),
@@ -127,14 +123,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
Int32Value_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Int32Value_descriptor_,
- Int32Value::default_instance_,
+ Int32Value::internal_default_instance(),
Int32Value_offsets_,
-1,
-1,
-1,
sizeof(Int32Value),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int32Value, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int32Value, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Int32Value, _internal_metadata_));
UInt32Value_descriptor_ = file->message_type(5);
static const int UInt32Value_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt32Value, value_),
@@ -142,14 +137,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
UInt32Value_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
UInt32Value_descriptor_,
- UInt32Value::default_instance_,
+ UInt32Value::internal_default_instance(),
UInt32Value_offsets_,
-1,
-1,
-1,
sizeof(UInt32Value),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt32Value, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt32Value, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UInt32Value, _internal_metadata_));
BoolValue_descriptor_ = file->message_type(6);
static const int BoolValue_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoolValue, value_),
@@ -157,14 +151,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
BoolValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
BoolValue_descriptor_,
- BoolValue::default_instance_,
+ BoolValue::internal_default_instance(),
BoolValue_offsets_,
-1,
-1,
-1,
sizeof(BoolValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoolValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoolValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoolValue, _internal_metadata_));
StringValue_descriptor_ = file->message_type(7);
static const int StringValue_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(StringValue, value_),
@@ -172,14 +165,13 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
StringValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
StringValue_descriptor_,
- StringValue::default_instance_,
+ StringValue::internal_default_instance(),
StringValue_offsets_,
-1,
-1,
-1,
sizeof(StringValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(StringValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(StringValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(StringValue, _internal_metadata_));
BytesValue_descriptor_ = file->message_type(8);
static const int BytesValue_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BytesValue, value_),
@@ -187,20 +179,19 @@ void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto() {
BytesValue_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
BytesValue_descriptor_,
- BytesValue::default_instance_,
+ BytesValue::internal_default_instance(),
BytesValue_offsets_,
-1,
-1,
-1,
sizeof(BytesValue),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BytesValue, _internal_metadata_),
- GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BytesValue, _is_default_instance_));
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BytesValue, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
-inline void protobuf_AssignDescriptorsOnce() {
+void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto);
}
@@ -209,55 +200,82 @@ void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- DoubleValue_descriptor_, &DoubleValue::default_instance());
+ DoubleValue_descriptor_, DoubleValue::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- FloatValue_descriptor_, &FloatValue::default_instance());
+ FloatValue_descriptor_, FloatValue::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Int64Value_descriptor_, &Int64Value::default_instance());
+ Int64Value_descriptor_, Int64Value::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- UInt64Value_descriptor_, &UInt64Value::default_instance());
+ UInt64Value_descriptor_, UInt64Value::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- Int32Value_descriptor_, &Int32Value::default_instance());
+ Int32Value_descriptor_, Int32Value::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- UInt32Value_descriptor_, &UInt32Value::default_instance());
+ UInt32Value_descriptor_, UInt32Value::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- BoolValue_descriptor_, &BoolValue::default_instance());
+ BoolValue_descriptor_, BoolValue::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- StringValue_descriptor_, &StringValue::default_instance());
+ StringValue_descriptor_, StringValue::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
- BytesValue_descriptor_, &BytesValue::default_instance());
+ BytesValue_descriptor_, BytesValue::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto() {
- delete DoubleValue::default_instance_;
+ DoubleValue_default_instance_.Shutdown();
delete DoubleValue_reflection_;
- delete FloatValue::default_instance_;
+ FloatValue_default_instance_.Shutdown();
delete FloatValue_reflection_;
- delete Int64Value::default_instance_;
+ Int64Value_default_instance_.Shutdown();
delete Int64Value_reflection_;
- delete UInt64Value::default_instance_;
+ UInt64Value_default_instance_.Shutdown();
delete UInt64Value_reflection_;
- delete Int32Value::default_instance_;
+ Int32Value_default_instance_.Shutdown();
delete Int32Value_reflection_;
- delete UInt32Value::default_instance_;
+ UInt32Value_default_instance_.Shutdown();
delete UInt32Value_reflection_;
- delete BoolValue::default_instance_;
+ BoolValue_default_instance_.Shutdown();
delete BoolValue_reflection_;
- delete StringValue::default_instance_;
+ StringValue_default_instance_.Shutdown();
delete StringValue_reflection_;
- delete BytesValue::default_instance_;
+ BytesValue_default_instance_.Shutdown();
delete BytesValue_reflection_;
}
-void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto() GOOGLE_ATTRIBUTE_COLD;
-void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto() {
- static bool already_here = false;
- if (already_here) return;
- already_here = true;
+void protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl() {
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ DoubleValue_default_instance_.DefaultConstruct();
+ FloatValue_default_instance_.DefaultConstruct();
+ Int64Value_default_instance_.DefaultConstruct();
+ UInt64Value_default_instance_.DefaultConstruct();
+ Int32Value_default_instance_.DefaultConstruct();
+ UInt32Value_default_instance_.DefaultConstruct();
+ BoolValue_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ StringValue_default_instance_.DefaultConstruct();
+ ::google::protobuf::internal::GetEmptyString();
+ BytesValue_default_instance_.DefaultConstruct();
+ DoubleValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+ FloatValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Int64Value_default_instance_.get_mutable()->InitAsDefaultInstance();
+ UInt64Value_default_instance_.get_mutable()->InitAsDefaultInstance();
+ Int32Value_default_instance_.get_mutable()->InitAsDefaultInstance();
+ UInt32Value_default_instance_.get_mutable()->InitAsDefaultInstance();
+ BoolValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+ StringValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+ BytesValue_default_instance_.get_mutable()->InitAsDefaultInstance();
+}
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_once_);
+void protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_once_,
+ &protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl);
+}
+void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\036google/protobuf/wrappers.proto\022\017google"
".protobuf\"\034\n\013DoubleValue\022\r\n\005value\030\001 \001(\001\""
@@ -266,34 +284,21 @@ void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto() {
"e\030\001 \001(\004\"\033\n\nInt32Value\022\r\n\005value\030\001 \001(\005\"\034\n\013"
"UInt32Value\022\r\n\005value\030\001 \001(\r\"\032\n\tBoolValue\022"
"\r\n\005value\030\001 \001(\010\"\034\n\013StringValue\022\r\n\005value\030\001"
- " \001(\t\"\033\n\nBytesValue\022\r\n\005value\030\001 \001(\014B\177\n\023com"
+ " \001(\t\"\033\n\nBytesValue\022\r\n\005value\030\001 \001(\014B|\n\023com"
".google.protobufB\rWrappersProtoP\001Z*githu"
- "b.com/golang/protobuf/ptypes/wrappers\240\001\001"
- "\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTyp"
- "esb\006proto3", 450);
+ "b.com/golang/protobuf/ptypes/wrappers\370\001\001"
+ "\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypesb"
+ "\006proto3", 447);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/wrappers.proto", &protobuf_RegisterTypes);
- DoubleValue::default_instance_ = new DoubleValue();
- FloatValue::default_instance_ = new FloatValue();
- Int64Value::default_instance_ = new Int64Value();
- UInt64Value::default_instance_ = new UInt64Value();
- Int32Value::default_instance_ = new Int32Value();
- UInt32Value::default_instance_ = new UInt32Value();
- BoolValue::default_instance_ = new BoolValue();
- StringValue::default_instance_ = new StringValue();
- BytesValue::default_instance_ = new BytesValue();
- DoubleValue::default_instance_->InitAsDefaultInstance();
- FloatValue::default_instance_->InitAsDefaultInstance();
- Int64Value::default_instance_->InitAsDefaultInstance();
- UInt64Value::default_instance_->InitAsDefaultInstance();
- Int32Value::default_instance_->InitAsDefaultInstance();
- UInt32Value::default_instance_->InitAsDefaultInstance();
- BoolValue::default_instance_->InitAsDefaultInstance();
- StringValue::default_instance_->InitAsDefaultInstance();
- BytesValue::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto);
}
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_once_);
+void protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_once_,
+ &protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl);
+}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2fwrappers_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2fwrappers_2eproto() {
@@ -301,6 +306,16 @@ struct StaticDescriptorInitializer_google_2fprotobuf_2fwrappers_2eproto {
}
} static_descriptor_initializer_google_2fprotobuf_2fwrappers_2eproto_;
+namespace {
+
+static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
+static void MergeFromFail(int line) {
+ ::google::protobuf::internal::MergeFromFail(__FILE__, line);
+}
+
+} // namespace
+
+
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
@@ -309,34 +324,35 @@ const int DoubleValue::kValueFieldNumber;
DoubleValue::DoubleValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.DoubleValue)
}
-
DoubleValue::DoubleValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue)
}
void DoubleValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
DoubleValue::DoubleValue(const DoubleValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.DoubleValue)
}
void DoubleValue::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = 0;
+ _cached_size_ = 0;
}
DoubleValue::~DoubleValue() {
@@ -345,12 +361,11 @@ DoubleValue::~DoubleValue() {
}
void DoubleValue::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void DoubleValue::ArenaDtor(void* object) {
@@ -370,11 +385,11 @@ const ::google::protobuf::Descriptor* DoubleValue::descriptor() {
}
const DoubleValue& DoubleValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-DoubleValue* DoubleValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<DoubleValue> DoubleValue_default_instance_;
DoubleValue* DoubleValue::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<DoubleValue>(arena);
@@ -398,10 +413,10 @@ bool DoubleValue::MergePartialFromCodedStream(
// optional double value = 1;
case 1: {
if (tag == 9) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -443,6 +458,7 @@ void DoubleValue::SerializeWithCachedSizes(
::google::protobuf::uint8* DoubleValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.DoubleValue)
// optional double value = 1;
if (this->value() != 0) {
@@ -453,27 +469,26 @@ void DoubleValue::SerializeWithCachedSizes(
return target;
}
-int DoubleValue::ByteSize() const {
+size_t DoubleValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.DoubleValue)
- int total_size = 0;
+ size_t total_size = 0;
// optional double value = 1;
if (this->value() != 0) {
total_size += 1 + 8;
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DoubleValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.DoubleValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const DoubleValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const DoubleValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const DoubleValue>(
&from);
if (source == NULL) {
@@ -481,15 +496,21 @@ void DoubleValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.DoubleValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void DoubleValue::MergeFrom(const DoubleValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.DoubleValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void DoubleValue::UnsafeMergeFrom(const DoubleValue& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -506,7 +527,7 @@ void DoubleValue::CopyFrom(const DoubleValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.DoubleValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool DoubleValue::IsInitialized() const {
@@ -520,7 +541,7 @@ void DoubleValue::Swap(DoubleValue* other) {
InternalSwap(other);
} else {
DoubleValue temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -551,16 +572,19 @@ void DoubleValue::InternalSwap(DoubleValue* other) {
void DoubleValue::clear_value() {
value_ = 0;
}
- double DoubleValue::value() const {
+double DoubleValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.DoubleValue.value)
return value_;
}
- void DoubleValue::set_value(double value) {
+void DoubleValue::set_value(double value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.DoubleValue.value)
}
+inline const DoubleValue* DoubleValue::internal_default_instance() {
+ return &DoubleValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -571,34 +595,35 @@ const int FloatValue::kValueFieldNumber;
FloatValue::FloatValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.FloatValue)
}
-
FloatValue::FloatValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue)
}
void FloatValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
FloatValue::FloatValue(const FloatValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.FloatValue)
}
void FloatValue::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = 0;
+ _cached_size_ = 0;
}
FloatValue::~FloatValue() {
@@ -607,12 +632,11 @@ FloatValue::~FloatValue() {
}
void FloatValue::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void FloatValue::ArenaDtor(void* object) {
@@ -632,11 +656,11 @@ const ::google::protobuf::Descriptor* FloatValue::descriptor() {
}
const FloatValue& FloatValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-FloatValue* FloatValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<FloatValue> FloatValue_default_instance_;
FloatValue* FloatValue::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<FloatValue>(arena);
@@ -660,10 +684,10 @@ bool FloatValue::MergePartialFromCodedStream(
// optional float value = 1;
case 1: {
if (tag == 13) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -705,6 +729,7 @@ void FloatValue::SerializeWithCachedSizes(
::google::protobuf::uint8* FloatValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.FloatValue)
// optional float value = 1;
if (this->value() != 0) {
@@ -715,27 +740,26 @@ void FloatValue::SerializeWithCachedSizes(
return target;
}
-int FloatValue::ByteSize() const {
+size_t FloatValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.FloatValue)
- int total_size = 0;
+ size_t total_size = 0;
// optional float value = 1;
if (this->value() != 0) {
total_size += 1 + 4;
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void FloatValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.FloatValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const FloatValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const FloatValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const FloatValue>(
&from);
if (source == NULL) {
@@ -743,15 +767,21 @@ void FloatValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.FloatValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void FloatValue::MergeFrom(const FloatValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.FloatValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void FloatValue::UnsafeMergeFrom(const FloatValue& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -768,7 +798,7 @@ void FloatValue::CopyFrom(const FloatValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.FloatValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool FloatValue::IsInitialized() const {
@@ -782,7 +812,7 @@ void FloatValue::Swap(FloatValue* other) {
InternalSwap(other);
} else {
FloatValue temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -813,16 +843,19 @@ void FloatValue::InternalSwap(FloatValue* other) {
void FloatValue::clear_value() {
value_ = 0;
}
- float FloatValue::value() const {
+float FloatValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.FloatValue.value)
return value_;
}
- void FloatValue::set_value(float value) {
+void FloatValue::set_value(float value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.FloatValue.value)
}
+inline const FloatValue* FloatValue::internal_default_instance() {
+ return &FloatValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -833,34 +866,35 @@ const int Int64Value::kValueFieldNumber;
Int64Value::Int64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Int64Value)
}
-
Int64Value::Int64Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value)
}
void Int64Value::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Int64Value::Int64Value(const Int64Value& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Int64Value)
}
void Int64Value::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = GOOGLE_LONGLONG(0);
+ _cached_size_ = 0;
}
Int64Value::~Int64Value() {
@@ -869,12 +903,11 @@ Int64Value::~Int64Value() {
}
void Int64Value::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void Int64Value::ArenaDtor(void* object) {
@@ -894,11 +927,11 @@ const ::google::protobuf::Descriptor* Int64Value::descriptor() {
}
const Int64Value& Int64Value::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-Int64Value* Int64Value::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Int64Value> Int64Value_default_instance_;
Int64Value* Int64Value::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<Int64Value>(arena);
@@ -922,10 +955,10 @@ bool Int64Value::MergePartialFromCodedStream(
// optional int64 value = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -967,6 +1000,7 @@ void Int64Value::SerializeWithCachedSizes(
::google::protobuf::uint8* Int64Value::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Int64Value)
// optional int64 value = 1;
if (this->value() != 0) {
@@ -977,9 +1011,9 @@ void Int64Value::SerializeWithCachedSizes(
return target;
}
-int Int64Value::ByteSize() const {
+size_t Int64Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Int64Value)
- int total_size = 0;
+ size_t total_size = 0;
// optional int64 value = 1;
if (this->value() != 0) {
@@ -988,18 +1022,17 @@ int Int64Value::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Int64Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Int64Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Int64Value* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Int64Value* source =
::google::protobuf::internal::DynamicCastToGenerated<const Int64Value>(
&from);
if (source == NULL) {
@@ -1007,15 +1040,21 @@ void Int64Value::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Int64Value)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Int64Value::MergeFrom(const Int64Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Int64Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Int64Value::UnsafeMergeFrom(const Int64Value& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -1032,7 +1071,7 @@ void Int64Value::CopyFrom(const Int64Value& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Int64Value)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Int64Value::IsInitialized() const {
@@ -1046,7 +1085,7 @@ void Int64Value::Swap(Int64Value* other) {
InternalSwap(other);
} else {
Int64Value temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -1077,16 +1116,19 @@ void Int64Value::InternalSwap(Int64Value* other) {
void Int64Value::clear_value() {
value_ = GOOGLE_LONGLONG(0);
}
- ::google::protobuf::int64 Int64Value::value() const {
+::google::protobuf::int64 Int64Value::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Int64Value.value)
return value_;
}
- void Int64Value::set_value(::google::protobuf::int64 value) {
+void Int64Value::set_value(::google::protobuf::int64 value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Int64Value.value)
}
+inline const Int64Value* Int64Value::internal_default_instance() {
+ return &Int64Value_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1097,34 +1139,35 @@ const int UInt64Value::kValueFieldNumber;
UInt64Value::UInt64Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UInt64Value)
}
-
UInt64Value::UInt64Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value)
}
void UInt64Value::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
UInt64Value::UInt64Value(const UInt64Value& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.UInt64Value)
}
void UInt64Value::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = GOOGLE_ULONGLONG(0);
+ _cached_size_ = 0;
}
UInt64Value::~UInt64Value() {
@@ -1133,12 +1176,11 @@ UInt64Value::~UInt64Value() {
}
void UInt64Value::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void UInt64Value::ArenaDtor(void* object) {
@@ -1158,11 +1200,11 @@ const ::google::protobuf::Descriptor* UInt64Value::descriptor() {
}
const UInt64Value& UInt64Value::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-UInt64Value* UInt64Value::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<UInt64Value> UInt64Value_default_instance_;
UInt64Value* UInt64Value::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<UInt64Value>(arena);
@@ -1186,10 +1228,10 @@ bool UInt64Value::MergePartialFromCodedStream(
// optional uint64 value = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -1231,6 +1273,7 @@ void UInt64Value::SerializeWithCachedSizes(
::google::protobuf::uint8* UInt64Value::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UInt64Value)
// optional uint64 value = 1;
if (this->value() != 0) {
@@ -1241,9 +1284,9 @@ void UInt64Value::SerializeWithCachedSizes(
return target;
}
-int UInt64Value::ByteSize() const {
+size_t UInt64Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.UInt64Value)
- int total_size = 0;
+ size_t total_size = 0;
// optional uint64 value = 1;
if (this->value() != 0) {
@@ -1252,18 +1295,17 @@ int UInt64Value::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void UInt64Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UInt64Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const UInt64Value* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const UInt64Value* source =
::google::protobuf::internal::DynamicCastToGenerated<const UInt64Value>(
&from);
if (source == NULL) {
@@ -1271,15 +1313,21 @@ void UInt64Value::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.UInt64Value)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void UInt64Value::MergeFrom(const UInt64Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UInt64Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void UInt64Value::UnsafeMergeFrom(const UInt64Value& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -1296,7 +1344,7 @@ void UInt64Value::CopyFrom(const UInt64Value& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.UInt64Value)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool UInt64Value::IsInitialized() const {
@@ -1310,7 +1358,7 @@ void UInt64Value::Swap(UInt64Value* other) {
InternalSwap(other);
} else {
UInt64Value temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -1341,16 +1389,19 @@ void UInt64Value::InternalSwap(UInt64Value* other) {
void UInt64Value::clear_value() {
value_ = GOOGLE_ULONGLONG(0);
}
- ::google::protobuf::uint64 UInt64Value::value() const {
+::google::protobuf::uint64 UInt64Value::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UInt64Value.value)
return value_;
}
- void UInt64Value::set_value(::google::protobuf::uint64 value) {
+void UInt64Value::set_value(::google::protobuf::uint64 value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UInt64Value.value)
}
+inline const UInt64Value* UInt64Value::internal_default_instance() {
+ return &UInt64Value_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1361,34 +1412,35 @@ const int Int32Value::kValueFieldNumber;
Int32Value::Int32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Int32Value)
}
-
Int32Value::Int32Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value)
}
void Int32Value::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
Int32Value::Int32Value(const Int32Value& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.Int32Value)
}
void Int32Value::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = 0;
+ _cached_size_ = 0;
}
Int32Value::~Int32Value() {
@@ -1397,12 +1449,11 @@ Int32Value::~Int32Value() {
}
void Int32Value::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void Int32Value::ArenaDtor(void* object) {
@@ -1422,11 +1473,11 @@ const ::google::protobuf::Descriptor* Int32Value::descriptor() {
}
const Int32Value& Int32Value::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-Int32Value* Int32Value::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<Int32Value> Int32Value_default_instance_;
Int32Value* Int32Value::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<Int32Value>(arena);
@@ -1450,10 +1501,10 @@ bool Int32Value::MergePartialFromCodedStream(
// optional int32 value = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -1495,6 +1546,7 @@ void Int32Value::SerializeWithCachedSizes(
::google::protobuf::uint8* Int32Value::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Int32Value)
// optional int32 value = 1;
if (this->value() != 0) {
@@ -1505,9 +1557,9 @@ void Int32Value::SerializeWithCachedSizes(
return target;
}
-int Int32Value::ByteSize() const {
+size_t Int32Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Int32Value)
- int total_size = 0;
+ size_t total_size = 0;
// optional int32 value = 1;
if (this->value() != 0) {
@@ -1516,18 +1568,17 @@ int Int32Value::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Int32Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Int32Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const Int32Value* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const Int32Value* source =
::google::protobuf::internal::DynamicCastToGenerated<const Int32Value>(
&from);
if (source == NULL) {
@@ -1535,15 +1586,21 @@ void Int32Value::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Int32Value)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void Int32Value::MergeFrom(const Int32Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Int32Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void Int32Value::UnsafeMergeFrom(const Int32Value& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -1560,7 +1617,7 @@ void Int32Value::CopyFrom(const Int32Value& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Int32Value)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool Int32Value::IsInitialized() const {
@@ -1574,7 +1631,7 @@ void Int32Value::Swap(Int32Value* other) {
InternalSwap(other);
} else {
Int32Value temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -1605,16 +1662,19 @@ void Int32Value::InternalSwap(Int32Value* other) {
void Int32Value::clear_value() {
value_ = 0;
}
- ::google::protobuf::int32 Int32Value::value() const {
+::google::protobuf::int32 Int32Value::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Int32Value.value)
return value_;
}
- void Int32Value::set_value(::google::protobuf::int32 value) {
+void Int32Value::set_value(::google::protobuf::int32 value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.Int32Value.value)
}
+inline const Int32Value* Int32Value::internal_default_instance() {
+ return &Int32Value_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1625,34 +1685,35 @@ const int UInt32Value::kValueFieldNumber;
UInt32Value::UInt32Value()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.UInt32Value)
}
-
UInt32Value::UInt32Value(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value)
}
void UInt32Value::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
UInt32Value::UInt32Value(const UInt32Value& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.UInt32Value)
}
void UInt32Value::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = 0u;
+ _cached_size_ = 0;
}
UInt32Value::~UInt32Value() {
@@ -1661,12 +1722,11 @@ UInt32Value::~UInt32Value() {
}
void UInt32Value::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void UInt32Value::ArenaDtor(void* object) {
@@ -1686,11 +1746,11 @@ const ::google::protobuf::Descriptor* UInt32Value::descriptor() {
}
const UInt32Value& UInt32Value::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-UInt32Value* UInt32Value::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<UInt32Value> UInt32Value_default_instance_;
UInt32Value* UInt32Value::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<UInt32Value>(arena);
@@ -1714,10 +1774,10 @@ bool UInt32Value::MergePartialFromCodedStream(
// optional uint32 value = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -1759,6 +1819,7 @@ void UInt32Value::SerializeWithCachedSizes(
::google::protobuf::uint8* UInt32Value::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.UInt32Value)
// optional uint32 value = 1;
if (this->value() != 0) {
@@ -1769,9 +1830,9 @@ void UInt32Value::SerializeWithCachedSizes(
return target;
}
-int UInt32Value::ByteSize() const {
+size_t UInt32Value::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.UInt32Value)
- int total_size = 0;
+ size_t total_size = 0;
// optional uint32 value = 1;
if (this->value() != 0) {
@@ -1780,18 +1841,17 @@ int UInt32Value::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void UInt32Value::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.UInt32Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const UInt32Value* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const UInt32Value* source =
::google::protobuf::internal::DynamicCastToGenerated<const UInt32Value>(
&from);
if (source == NULL) {
@@ -1799,15 +1859,21 @@ void UInt32Value::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.UInt32Value)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void UInt32Value::MergeFrom(const UInt32Value& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.UInt32Value)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void UInt32Value::UnsafeMergeFrom(const UInt32Value& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -1824,7 +1890,7 @@ void UInt32Value::CopyFrom(const UInt32Value& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.UInt32Value)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool UInt32Value::IsInitialized() const {
@@ -1838,7 +1904,7 @@ void UInt32Value::Swap(UInt32Value* other) {
InternalSwap(other);
} else {
UInt32Value temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -1869,16 +1935,19 @@ void UInt32Value::InternalSwap(UInt32Value* other) {
void UInt32Value::clear_value() {
value_ = 0u;
}
- ::google::protobuf::uint32 UInt32Value::value() const {
+::google::protobuf::uint32 UInt32Value::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.UInt32Value.value)
return value_;
}
- void UInt32Value::set_value(::google::protobuf::uint32 value) {
+void UInt32Value::set_value(::google::protobuf::uint32 value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.UInt32Value.value)
}
+inline const UInt32Value* UInt32Value::internal_default_instance() {
+ return &UInt32Value_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -1889,34 +1958,35 @@ const int BoolValue::kValueFieldNumber;
BoolValue::BoolValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.BoolValue)
}
-
BoolValue::BoolValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue)
}
void BoolValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
BoolValue::BoolValue(const BoolValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.BoolValue)
}
void BoolValue::SharedCtor() {
- _is_default_instance_ = false;
- _cached_size_ = 0;
value_ = false;
+ _cached_size_ = 0;
}
BoolValue::~BoolValue() {
@@ -1925,12 +1995,11 @@ BoolValue::~BoolValue() {
}
void BoolValue::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- if (this != default_instance_) {
- }
}
void BoolValue::ArenaDtor(void* object) {
@@ -1950,11 +2019,11 @@ const ::google::protobuf::Descriptor* BoolValue::descriptor() {
}
const BoolValue& BoolValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-BoolValue* BoolValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<BoolValue> BoolValue_default_instance_;
BoolValue* BoolValue::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<BoolValue>(arena);
@@ -1978,10 +2047,10 @@ bool BoolValue::MergePartialFromCodedStream(
// optional bool value = 1;
case 1: {
if (tag == 8) {
+
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>(
input, &value_)));
-
} else {
goto handle_unusual;
}
@@ -2023,6 +2092,7 @@ void BoolValue::SerializeWithCachedSizes(
::google::protobuf::uint8* BoolValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.BoolValue)
// optional bool value = 1;
if (this->value() != 0) {
@@ -2033,27 +2103,26 @@ void BoolValue::SerializeWithCachedSizes(
return target;
}
-int BoolValue::ByteSize() const {
+size_t BoolValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.BoolValue)
- int total_size = 0;
+ size_t total_size = 0;
// optional bool value = 1;
if (this->value() != 0) {
total_size += 1 + 1;
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BoolValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.BoolValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const BoolValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const BoolValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const BoolValue>(
&from);
if (source == NULL) {
@@ -2061,15 +2130,21 @@ void BoolValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.BoolValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void BoolValue::MergeFrom(const BoolValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.BoolValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void BoolValue::UnsafeMergeFrom(const BoolValue& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value() != 0) {
set_value(from.value());
}
@@ -2086,7 +2161,7 @@ void BoolValue::CopyFrom(const BoolValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.BoolValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool BoolValue::IsInitialized() const {
@@ -2100,7 +2175,7 @@ void BoolValue::Swap(BoolValue* other) {
InternalSwap(other);
} else {
BoolValue temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -2131,16 +2206,19 @@ void BoolValue::InternalSwap(BoolValue* other) {
void BoolValue::clear_value() {
value_ = false;
}
- bool BoolValue::value() const {
+bool BoolValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.BoolValue.value)
return value_;
}
- void BoolValue::set_value(bool value) {
+void BoolValue::set_value(bool value) {
value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.BoolValue.value)
}
+inline const BoolValue* BoolValue::internal_default_instance() {
+ return &BoolValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -2151,35 +2229,35 @@ const int StringValue::kValueFieldNumber;
StringValue::StringValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.StringValue)
}
-
StringValue::StringValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue)
}
void StringValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
StringValue::StringValue(const StringValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.StringValue)
}
void StringValue::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _cached_size_ = 0;
}
StringValue::~StringValue() {
@@ -2188,13 +2266,12 @@ StringValue::~StringValue() {
}
void StringValue::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- if (this != default_instance_) {
- }
+ value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
}
void StringValue::ArenaDtor(void* object) {
@@ -2214,11 +2291,11 @@ const ::google::protobuf::Descriptor* StringValue::descriptor() {
}
const StringValue& StringValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-StringValue* StringValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<StringValue> StringValue_default_instance_;
StringValue* StringValue::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<StringValue>(arena);
@@ -2294,6 +2371,7 @@ void StringValue::SerializeWithCachedSizes(
::google::protobuf::uint8* StringValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.StringValue)
// optional string value = 1;
if (this->value().size() > 0) {
@@ -2310,9 +2388,9 @@ void StringValue::SerializeWithCachedSizes(
return target;
}
-int StringValue::ByteSize() const {
+size_t StringValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.StringValue)
- int total_size = 0;
+ size_t total_size = 0;
// optional string value = 1;
if (this->value().size() > 0) {
@@ -2321,18 +2399,17 @@ int StringValue::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void StringValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.StringValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const StringValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const StringValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const StringValue>(
&from);
if (source == NULL) {
@@ -2340,15 +2417,21 @@ void StringValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.StringValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void StringValue::MergeFrom(const StringValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.StringValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void StringValue::UnsafeMergeFrom(const StringValue& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value().size() > 0) {
set_value(from.value());
}
@@ -2365,7 +2448,7 @@ void StringValue::CopyFrom(const StringValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.StringValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool StringValue::IsInitialized() const {
@@ -2379,7 +2462,7 @@ void StringValue::Swap(StringValue* other) {
InternalSwap(other);
} else {
StringValue temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -2410,46 +2493,46 @@ void StringValue::InternalSwap(StringValue* other) {
void StringValue::clear_value() {
value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& StringValue::value() const {
+const ::std::string& StringValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.StringValue.value)
return value_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void StringValue::set_value(const ::std::string& value) {
+void StringValue::set_value(const ::std::string& value) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.StringValue.value)
}
- void StringValue::set_value(const char* value) {
+void StringValue::set_value(const char* value) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.StringValue.value)
}
- void StringValue::set_value(const char* value,
+void StringValue::set_value(const char* value,
size_t size) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.StringValue.value)
}
- ::std::string* StringValue::mutable_value() {
+::std::string* StringValue::mutable_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.StringValue.value)
return value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* StringValue::release_value() {
+::std::string* StringValue::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.StringValue.value)
return value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* StringValue::unsafe_arena_release_value() {
+::std::string* StringValue::unsafe_arena_release_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.StringValue.value)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
- void StringValue::set_allocated_value(::std::string* value) {
+void StringValue::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
@@ -2459,7 +2542,7 @@ void StringValue::clear_value() {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.StringValue.value)
}
- void StringValue::unsafe_arena_set_allocated_value(
+void StringValue::unsafe_arena_set_allocated_value(
::std::string* value) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (value != NULL) {
@@ -2472,6 +2555,9 @@ void StringValue::clear_value() {
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.StringValue.value)
}
+inline const StringValue* StringValue::internal_default_instance() {
+ return &StringValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
@@ -2482,35 +2568,35 @@ const int BytesValue::kValueFieldNumber;
BytesValue::BytesValue()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
+ if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.BytesValue)
}
-
BytesValue::BytesValue(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
+#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue)
}
void BytesValue::InitAsDefaultInstance() {
- _is_default_instance_ = true;
}
BytesValue::BytesValue(const BytesValue& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.BytesValue)
}
void BytesValue::SharedCtor() {
- _is_default_instance_ = false;
- ::google::protobuf::internal::GetEmptyString();
- _cached_size_ = 0;
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ _cached_size_ = 0;
}
BytesValue::~BytesValue() {
@@ -2519,13 +2605,12 @@ BytesValue::~BytesValue() {
}
void BytesValue::SharedDtor() {
- if (GetArenaNoVirtual() != NULL) {
+ ::google::protobuf::Arena* arena = GetArenaNoVirtual();
+ if (arena != NULL) {
return;
}
- value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
- if (this != default_instance_) {
- }
+ value_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
}
void BytesValue::ArenaDtor(void* object) {
@@ -2545,11 +2630,11 @@ const ::google::protobuf::Descriptor* BytesValue::descriptor() {
}
const BytesValue& BytesValue::default_instance() {
- if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
- return *default_instance_;
+ protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
+ return *internal_default_instance();
}
-BytesValue* BytesValue::default_instance_ = NULL;
+::google::protobuf::internal::ExplicitlyConstructed<BytesValue> BytesValue_default_instance_;
BytesValue* BytesValue::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<BytesValue>(arena);
@@ -2617,6 +2702,7 @@ void BytesValue::SerializeWithCachedSizes(
::google::protobuf::uint8* BytesValue::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
+ (void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.BytesValue)
// optional bytes value = 1;
if (this->value().size() > 0) {
@@ -2629,9 +2715,9 @@ void BytesValue::SerializeWithCachedSizes(
return target;
}
-int BytesValue::ByteSize() const {
+size_t BytesValue::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.BytesValue)
- int total_size = 0;
+ size_t total_size = 0;
// optional bytes value = 1;
if (this->value().size() > 0) {
@@ -2640,18 +2726,17 @@ int BytesValue::ByteSize() const {
this->value());
}
+ int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
- _cached_size_ = total_size;
+ _cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BytesValue::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.BytesValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
- }
- const BytesValue* source =
+ if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
+ const BytesValue* source =
::google::protobuf::internal::DynamicCastToGenerated<const BytesValue>(
&from);
if (source == NULL) {
@@ -2659,15 +2744,21 @@ void BytesValue::MergeFrom(const ::google::protobuf::Message& from) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.BytesValue)
- MergeFrom(*source);
+ UnsafeMergeFrom(*source);
}
}
void BytesValue::MergeFrom(const BytesValue& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.BytesValue)
- if (GOOGLE_PREDICT_FALSE(&from == this)) {
- ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
+ if (GOOGLE_PREDICT_TRUE(&from != this)) {
+ UnsafeMergeFrom(from);
+ } else {
+ MergeFromFail(__LINE__);
}
+}
+
+void BytesValue::UnsafeMergeFrom(const BytesValue& from) {
+ GOOGLE_DCHECK(&from != this);
if (from.value().size() > 0) {
set_value(from.value());
}
@@ -2684,7 +2775,7 @@ void BytesValue::CopyFrom(const BytesValue& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.BytesValue)
if (&from == this) return;
Clear();
- MergeFrom(from);
+ UnsafeMergeFrom(from);
}
bool BytesValue::IsInitialized() const {
@@ -2698,7 +2789,7 @@ void BytesValue::Swap(BytesValue* other) {
InternalSwap(other);
} else {
BytesValue temp;
- temp.MergeFrom(*this);
+ temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
@@ -2729,46 +2820,46 @@ void BytesValue::InternalSwap(BytesValue* other) {
void BytesValue::clear_value() {
value_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- const ::std::string& BytesValue::value() const {
+const ::std::string& BytesValue::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.BytesValue.value)
return value_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
- void BytesValue::set_value(const ::std::string& value) {
+void BytesValue::set_value(const ::std::string& value) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:google.protobuf.BytesValue.value)
}
- void BytesValue::set_value(const char* value) {
+void BytesValue::set_value(const char* value) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:google.protobuf.BytesValue.value)
}
- void BytesValue::set_value(const void* value,
+void BytesValue::set_value(const void* value,
size_t size) {
value_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:google.protobuf.BytesValue.value)
}
- ::std::string* BytesValue::mutable_value() {
+::std::string* BytesValue::mutable_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.BytesValue.value)
return value_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* BytesValue::release_value() {
+::std::string* BytesValue::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.BytesValue.value)
return value_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
- ::std::string* BytesValue::unsafe_arena_release_value() {
+::std::string* BytesValue::unsafe_arena_release_value() {
// @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.BytesValue.value)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return value_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
- void BytesValue::set_allocated_value(::std::string* value) {
+void BytesValue::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
@@ -2778,7 +2869,7 @@ void BytesValue::clear_value() {
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:google.protobuf.BytesValue.value)
}
- void BytesValue::unsafe_arena_set_allocated_value(
+void BytesValue::unsafe_arena_set_allocated_value(
::std::string* value) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (value != NULL) {
@@ -2791,6 +2882,9 @@ void BytesValue::clear_value() {
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.BytesValue.value)
}
+inline const BytesValue* BytesValue::internal_default_instance() {
+ return &BytesValue_default_instance_.get();
+}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h
index 73f8ff62..568f8669 100644
--- a/src/google/protobuf/wrappers.pb.h
+++ b/src/google/protobuf/wrappers.pb.h
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
-#if GOOGLE_PROTOBUF_VERSION < 3000000
+#if GOOGLE_PROTOBUF_VERSION < 3001000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
-#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -34,6 +34,7 @@ namespace protobuf {
// Internal implementation detail -- do not call these.
void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
@@ -68,6 +69,8 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const DoubleValue& default_instance();
+ static const DoubleValue* internal_default_instance();
+
void UnsafeArenaSwap(DoubleValue* other);
void Swap(DoubleValue* other);
@@ -83,7 +86,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -99,6 +102,7 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(DoubleValue* other);
+ void UnsafeMergeFrom(const DoubleValue& from);
protected:
explicit DoubleValue(::google::protobuf::Arena* arena);
private:
@@ -132,16 +136,17 @@ class LIBPROTOBUF_EXPORT DoubleValue : public ::google::protobuf::Message /* @@p
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
double value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static DoubleValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<DoubleValue> DoubleValue_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FloatValue) */ {
@@ -163,6 +168,8 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const FloatValue& default_instance();
+ static const FloatValue* internal_default_instance();
+
void UnsafeArenaSwap(FloatValue* other);
void Swap(FloatValue* other);
@@ -178,7 +185,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -194,6 +201,7 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(FloatValue* other);
+ void UnsafeMergeFrom(const FloatValue& from);
protected:
explicit FloatValue(::google::protobuf::Arena* arena);
private:
@@ -227,16 +235,17 @@ class LIBPROTOBUF_EXPORT FloatValue : public ::google::protobuf::Message /* @@pr
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
float value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static FloatValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<FloatValue> FloatValue_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int64Value) */ {
@@ -258,6 +267,8 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const Int64Value& default_instance();
+ static const Int64Value* internal_default_instance();
+
void UnsafeArenaSwap(Int64Value* other);
void Swap(Int64Value* other);
@@ -273,7 +284,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -289,6 +300,7 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Int64Value* other);
+ void UnsafeMergeFrom(const Int64Value& from);
protected:
explicit Int64Value(::google::protobuf::Arena* arena);
private:
@@ -322,16 +334,17 @@ class LIBPROTOBUF_EXPORT Int64Value : public ::google::protobuf::Message /* @@pr
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::int64 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static Int64Value* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Int64Value> Int64Value_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt64Value) */ {
@@ -353,6 +366,8 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const UInt64Value& default_instance();
+ static const UInt64Value* internal_default_instance();
+
void UnsafeArenaSwap(UInt64Value* other);
void Swap(UInt64Value* other);
@@ -368,7 +383,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -384,6 +399,7 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(UInt64Value* other);
+ void UnsafeMergeFrom(const UInt64Value& from);
protected:
explicit UInt64Value(::google::protobuf::Arena* arena);
private:
@@ -417,16 +433,17 @@ class LIBPROTOBUF_EXPORT UInt64Value : public ::google::protobuf::Message /* @@p
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::uint64 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static UInt64Value* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<UInt64Value> UInt64Value_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int32Value) */ {
@@ -448,6 +465,8 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const Int32Value& default_instance();
+ static const Int32Value* internal_default_instance();
+
void UnsafeArenaSwap(Int32Value* other);
void Swap(Int32Value* other);
@@ -463,7 +482,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -479,6 +498,7 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(Int32Value* other);
+ void UnsafeMergeFrom(const Int32Value& from);
protected:
explicit Int32Value(::google::protobuf::Arena* arena);
private:
@@ -512,16 +532,17 @@ class LIBPROTOBUF_EXPORT Int32Value : public ::google::protobuf::Message /* @@pr
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::int32 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static Int32Value* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<Int32Value> Int32Value_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt32Value) */ {
@@ -543,6 +564,8 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const UInt32Value& default_instance();
+ static const UInt32Value* internal_default_instance();
+
void UnsafeArenaSwap(UInt32Value* other);
void Swap(UInt32Value* other);
@@ -558,7 +581,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -574,6 +597,7 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(UInt32Value* other);
+ void UnsafeMergeFrom(const UInt32Value& from);
protected:
explicit UInt32Value(::google::protobuf::Arena* arena);
private:
@@ -607,16 +631,17 @@ class LIBPROTOBUF_EXPORT UInt32Value : public ::google::protobuf::Message /* @@p
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::uint32 value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static UInt32Value* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<UInt32Value> UInt32Value_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BoolValue) */ {
@@ -638,6 +663,8 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
static const ::google::protobuf::Descriptor* descriptor();
static const BoolValue& default_instance();
+ static const BoolValue* internal_default_instance();
+
void UnsafeArenaSwap(BoolValue* other);
void Swap(BoolValue* other);
@@ -653,7 +680,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -669,6 +696,7 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(BoolValue* other);
+ void UnsafeMergeFrom(const BoolValue& from);
protected:
explicit BoolValue(::google::protobuf::Arena* arena);
private:
@@ -702,16 +730,17 @@ class LIBPROTOBUF_EXPORT BoolValue : public ::google::protobuf::Message /* @@pro
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
bool value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static BoolValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<BoolValue> BoolValue_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.StringValue) */ {
@@ -733,6 +762,8 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
static const ::google::protobuf::Descriptor* descriptor();
static const StringValue& default_instance();
+ static const StringValue* internal_default_instance();
+
void UnsafeArenaSwap(StringValue* other);
void Swap(StringValue* other);
@@ -748,7 +779,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -764,6 +795,7 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(StringValue* other);
+ void UnsafeMergeFrom(const StringValue& from);
protected:
explicit StringValue(::google::protobuf::Arena* arena);
private:
@@ -805,16 +837,17 @@ class LIBPROTOBUF_EXPORT StringValue : public ::google::protobuf::Message /* @@p
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static StringValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<StringValue> StringValue_default_instance_;
+
// -------------------------------------------------------------------
class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BytesValue) */ {
@@ -836,6 +869,8 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
static const ::google::protobuf::Descriptor* descriptor();
static const BytesValue& default_instance();
+ static const BytesValue* internal_default_instance();
+
void UnsafeArenaSwap(BytesValue* other);
void Swap(BytesValue* other);
@@ -851,7 +886,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
void Clear();
bool IsInitialized() const;
- int ByteSize() const;
+ size_t ByteSizeLong() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
@@ -867,6 +902,7 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(BytesValue* other);
+ void UnsafeMergeFrom(const BytesValue& from);
protected:
explicit BytesValue(::google::protobuf::Arena* arena);
private:
@@ -908,16 +944,17 @@ class LIBPROTOBUF_EXPORT BytesValue : public ::google::protobuf::Message /* @@pr
friend class ::google::protobuf::Arena;
typedef void InternalArenaConstructable_;
typedef void DestructorSkippable_;
- bool _is_default_instance_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
- friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto();
+ friend void LIBPROTOBUF_EXPORT protobuf_InitDefaults_google_2fprotobuf_2fwrappers_2eproto_impl();
+ friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fwrappers_2eproto_impl();
friend void protobuf_AssignDesc_google_2fprotobuf_2fwrappers_2eproto();
friend void protobuf_ShutdownFile_google_2fprotobuf_2fwrappers_2eproto();
void InitAsDefaultInstance();
- static BytesValue* default_instance_;
};
+extern ::google::protobuf::internal::ExplicitlyConstructed<BytesValue> BytesValue_default_instance_;
+
// ===================================================================
@@ -940,6 +977,9 @@ inline void DoubleValue::set_value(double value) {
// @@protoc_insertion_point(field_set:google.protobuf.DoubleValue.value)
}
+inline const DoubleValue* DoubleValue::internal_default_instance() {
+ return &DoubleValue_default_instance_.get();
+}
// -------------------------------------------------------------------
// FloatValue
@@ -958,6 +998,9 @@ inline void FloatValue::set_value(float value) {
// @@protoc_insertion_point(field_set:google.protobuf.FloatValue.value)
}
+inline const FloatValue* FloatValue::internal_default_instance() {
+ return &FloatValue_default_instance_.get();
+}
// -------------------------------------------------------------------
// Int64Value
@@ -976,6 +1019,9 @@ inline void Int64Value::set_value(::google::protobuf::int64 value) {
// @@protoc_insertion_point(field_set:google.protobuf.Int64Value.value)
}
+inline const Int64Value* Int64Value::internal_default_instance() {
+ return &Int64Value_default_instance_.get();
+}
// -------------------------------------------------------------------
// UInt64Value
@@ -994,6 +1040,9 @@ inline void UInt64Value::set_value(::google::protobuf::uint64 value) {
// @@protoc_insertion_point(field_set:google.protobuf.UInt64Value.value)
}
+inline const UInt64Value* UInt64Value::internal_default_instance() {
+ return &UInt64Value_default_instance_.get();
+}
// -------------------------------------------------------------------
// Int32Value
@@ -1012,6 +1061,9 @@ inline void Int32Value::set_value(::google::protobuf::int32 value) {
// @@protoc_insertion_point(field_set:google.protobuf.Int32Value.value)
}
+inline const Int32Value* Int32Value::internal_default_instance() {
+ return &Int32Value_default_instance_.get();
+}
// -------------------------------------------------------------------
// UInt32Value
@@ -1030,6 +1082,9 @@ inline void UInt32Value::set_value(::google::protobuf::uint32 value) {
// @@protoc_insertion_point(field_set:google.protobuf.UInt32Value.value)
}
+inline const UInt32Value* UInt32Value::internal_default_instance() {
+ return &UInt32Value_default_instance_.get();
+}
// -------------------------------------------------------------------
// BoolValue
@@ -1048,6 +1103,9 @@ inline void BoolValue::set_value(bool value) {
// @@protoc_insertion_point(field_set:google.protobuf.BoolValue.value)
}
+inline const BoolValue* BoolValue::internal_default_instance() {
+ return &BoolValue_default_instance_.get();
+}
// -------------------------------------------------------------------
// StringValue
@@ -1118,6 +1176,9 @@ inline void StringValue::unsafe_arena_set_allocated_value(
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.StringValue.value)
}
+inline const StringValue* StringValue::internal_default_instance() {
+ return &StringValue_default_instance_.get();
+}
// -------------------------------------------------------------------
// BytesValue
@@ -1188,6 +1249,9 @@ inline void BytesValue::unsafe_arena_set_allocated_value(
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.BytesValue.value)
}
+inline const BytesValue* BytesValue::internal_default_instance() {
+ return &BytesValue_default_instance_.get();
+}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
diff --git a/src/google/protobuf/wrappers.proto b/src/google/protobuf/wrappers.proto
index 4828ad9a..01947639 100644
--- a/src/google/protobuf/wrappers.proto
+++ b/src/google/protobuf/wrappers.proto
@@ -43,7 +43,6 @@ option go_package = "github.com/golang/protobuf/ptypes/wrappers";
option java_package = "com.google.protobuf";
option java_outer_classname = "WrappersProto";
option java_multiple_files = true;
-option java_generate_equals_and_hash = true;
option objc_class_prefix = "GPB";
// Wrapper message for `double`.
diff --git a/tests.sh b/tests.sh
index 9e95f2b7..4ac6b7c6 100755
--- a/tests.sh
+++ b/tests.sh
@@ -28,7 +28,8 @@ internal_build_cpp() {
fi
./autogen.sh
- ./configure
+ ./configure CXXFLAGS="-fPIC" # -fPIC is needed for python cpp test.
+ # See python/setup.py for more details
make -j2
}
@@ -38,6 +39,9 @@ build_cpp() {
cd conformance && make test_cpp && cd ..
# 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 ..
}
@@ -331,6 +335,129 @@ build_javascript() {
cd js && npm install && npm test && cd ..
}
+use_php() {
+ VERSION=$1
+ PHP=`which php`
+ PHP_CONFIG=`which php-config`
+ PHPIZE=`which phpize`
+ rm $PHP
+ rm $PHP_CONFIG
+ rm $PHPIZE
+ cp "/usr/bin/php$VERSION" $PHP
+ cp "/usr/bin/php-config$VERSION" $PHP_CONFIG
+ cp "/usr/bin/phpize$VERSION" $PHPIZE
+}
+
+use_php_zts() {
+ VERSION=$1
+ PHP=`which php`
+ PHP_CONFIG=`which php-config`
+ PHPIZE=`which phpize`
+ ln -sfn "/usr/local/php-${VERSION}-zts/bin/php" $PHP
+ ln -sfn "/usr/local/php-${VERSION}-zts/bin/php-config" $PHP_CONFIG
+ ln -sfn "/usr/local/php-${VERSION}-zts/bin/phpize" $PHPIZE
+}
+
+use_php_bc() {
+ VERSION=$1
+ PHP=`which php`
+ PHP_CONFIG=`which php-config`
+ PHPIZE=`which phpize`
+ ln -sfn "/usr/local/php-${VERSION}-bc/bin/php" $PHP
+ ln -sfn "/usr/local/php-${VERSION}-bc/bin/php-config" $PHP_CONFIG
+ ln -sfn "/usr/local/php-${VERSION}-bc/bin/phpize" $PHPIZE
+}
+
+build_php5.5() {
+ use_php 5.5
+ rm -rf vendor
+ cp -r /usr/local/vendor-5.5 vendor
+ ./vendor/bin/phpunit
+}
+
+build_php5.5_c() {
+ use_php 5.5
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+}
+
+build_php5.5_zts_c() {
+ use_php_zts 5.5
+ wget https://phar.phpunit.de/phpunit-old.phar -O /usr/bin/phpunit
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+}
+
+build_php5.5_32() {
+ use_php_bc 5.5
+ rm -rf vendor
+ cp -r /usr/local/vendor-5.5 vendor
+ ./vendor/bin/phpunit
+}
+
+build_php5.5_c_32() {
+ use_php_bc 5.5
+ wget https://phar.phpunit.de/phpunit-old.phar -O /usr/bin/phpunit
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+}
+
+build_php5.6() {
+ use_php 5.6
+ rm -rf vendor
+ cp -r /usr/local/vendor-5.6 vendor
+ ./vendor/bin/phpunit
+}
+
+build_php5.6_c() {
+ use_php 5.6
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+}
+
+build_php5.6_mac() {
+ # Install PHP
+ curl -s https://php-osx.liip.ch/install.sh | bash -s 5.6
+ PHP_FOLDER=`find /usr/local -type d -name "php5-5.6*"` # The folder name may change upon time
+ export PATH="$PHP_FOLDER/bin:$PATH"
+
+ # Install phpunit
+ curl https://phar.phpunit.de/phpunit.phar -L -o phpunit.phar
+ chmod +x phpunit.phar
+ sudo mv phpunit.phar /usr/local/bin/phpunit
+
+ # Install valgrind
+ echo "#! /bin/bash" > valgrind
+ chmod ug+x valgrind
+ sudo mv valgrind /usr/local/bin/valgrind
+
+ # Test
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+}
+
+build_php7.0() {
+ use_php 7.0
+ rm -rf vendor
+ cp -r /usr/local/vendor-7.0 vendor
+ ./vendor/bin/phpunit
+}
+
+build_php7.0_c() {
+ use_php 7.0
+ cd php/tests && /bin/bash ./test.sh && cd ../..
+}
+
+build_php_all() {
+ build_php5.5
+ build_php5.6
+ build_php7.0
+ build_php5.5_c
+ build_php5.6_c
+ # build_php7.0_c
+ build_php5.5_zts_c
+}
+
+build_php_all_32() {
+ build_php5.5_32
+ build_php5.5_c_32
+}
+
# Note: travis currently does not support testing more than one language so the
# .travis.yml cheats and claims to only be cpp. If they add multiple language
# support, this should probably get updated to install steps and/or
@@ -361,7 +488,14 @@ Usage: $0 { cpp |
ruby21 |
ruby22 |
jruby |
- ruby_all)
+ ruby_all |
+ php5.5 |
+ php5.5_c |
+ php5.6 |
+ php5.6_c |
+ php7.0 |
+ php7.0_c |
+ php_all)
"
exit 1
fi
diff --git a/third_party/benchmark b/third_party/benchmark
new file mode 160000
+Subproject 360e66c1c4777c99402cf8cd535aa510fee1657